'use strict';
(function (exports) {
    /**
     * 胡牌类型（4003）
     * @tpye {Object}
     * */
    majiang.HuType = {
        LiuJu: 0,          // 流局
        ZiMo: 1,           // 自摸
        DianPao: 2,        // 点炮
        WangDiao: 3,       // 王钓
        WangDiaoWang: 4,   // 王钓王
        WangChuang: 5,     // 王闯
        WangChuangWang: 6  // 王闯王
    };

    /**
     * 房间状态
     * @tpye {Object}
     * */
    majiang.RoomState = {
        NONE: 0,
        CREATED: 1,
        ONGOING: 2,
        ENDED: 3,
        JIESAN: 4,
        DELETIN: 5
    };

    /**
     * 可胡牌类型（4005）
     * @type {Object}
     * */
    majiang.Hu = {
        ZiMo: 0,           // 自摸
        WangDiao: 1,       // 王钓
        WangDiaoWang: 2,   // 王钓王
        WangChuang: 3,     // 王闯
        WangChuangWang: 4  // 王闯王
    };

    var signal1 = majiang.res.signal1;
    var signal2 = majiang.res.signal2;
    var signal3 = majiang.res.signal3;
    var signal4 = majiang.res.signal4;
    var signal5 = majiang.res.signal5;

    var lb_gang = majiang.res.lb_gang_png;
    var lb_lai = majiang.res.lb_lai_png;
    var lb_pi = majiang.res.lb_pi_png;
    var lb_gui = majiang.res.lb_gui_png;

    var ORIENTATION = {
        0: '东',
        1: '南',
        2: '西',
        3: '北'

    };
    var BatteryTextures = {
        'battery1': majiang.res.battery_1,
        'battery2': majiang.res.battery_2,
        'battery3': majiang.res.battery_3,
        'battery4': majiang.res.battery_4,
        'battery5': majiang.res.battery_5
    };
    var $ = null;

    var PAINAMES = ['', '一万', '二万', '三万', '四万', '五万', '六万', '七万', '八万', '九万', '一条', '二条', '三条', '四条', '五条', '六条', '七条', '八条', '九条', '一筒', '二筒', '三筒', '四筒', '五筒', '六筒', '七筒', '八筒', '九筒'];


    // CONST
    //发牌动画延时
    var FAPAI_ANIM_DELAY = 0.04;
    //发牌动画持续时间
    var FAPAI_ANIM_DURATION = 0.2;
    //摸牌动画持续时间
    var MOPAI_ANIM_DURATION = 0.3;
    var UPDOWNPAI_ANIM_DURATION = 0.088;
    //牌向上偏移距离（当单机牌时）
    var UPPAI_Y = 30;
    var CHUPAI_MID_NODE_SCALE_MAP = {0: 1.2, 2: 1.2, 1: 1.2, 3: 1.2};

    var MAP2PNUM = {1: 4, 2: 3};

    var OP_CHI = 1;
    var OP_PENG = 2;
    var OP_GANG = 3;
    var OP_HU = 4;
    var OP_PASS = 5;
    var OP_TING = 6;
    var OP_LIANG = 7;
    var OP_KAIGANG = 50;
    var OP_XIAOHU = 51;

    //创建
    var ROOM_STATE_CREATED = 1;
    //开始游戏
    var ROOM_STATE_ONGOING = 2;
    //结束游戏
    var ROOM_STATE_ENDED = 3;

    var posConf = {
        headPosBak: {}
        , paiA0PosBak: {}
        , paiA0ScaleBak: {}
        , paiADistance: []
        , paiALiangDistance: [0.5, 3.5, 0, -3.5]
        , paiMopaiDistance: {0: 16, 1: 40, 2: 34, 3: 40}
        , paiGDistance: []
        , paiUsedDistance: []
        , paiUsedZOrder: {
            0: {0: -1, 10: 0, 20: 1, 30: 2, 40: 3, 50: 4, 60: 5}
            , 1: {0: -1, 10: -1, 20: -1, 30: -1, 40: -1, 50: -1, 60: -1}
            , 2: {0: 0, 10: -1, 20: -2, 30: -3, 40: -4, 50: -5, 60: -6}
            , 3: {0: 0, 10: 1, 20: 2, 30: 3, 40: 4, 50: 5, 60: 6}
        }
        , cpghgPositionX: {
            2: [660, 920], 3: [425, 700, 960], 4: [320, 580, 840, 1070],
            5: [210, 460, 700, 940, 1130], 6: [210, 460, 700, 940, {x: 700, y: 360}, 1180]
        }
        , upPaiPositionY: null
        , downPaiPositionY: null
        , groupWidth: {}
        , groupHeight: {}
        , groupFourWidth: {}
        , groupFourHeight: {}
        , gangForthPaiPos: {}//杠的第四张牌位置
        , groupDistance: {0: -5, 1: -6, 2: 16, 3: -6}// 吃碰杠胡之间的距离
        , groupToFirstPaiDistance: {0: 1, 1: -24, 2: 26, 3: -24}// 吃碰杠胡和手牌的距离

        , paiPos: {}

        , ltqpPos: {}
        , ltqpRect: {
            0: cc.rect(0, 0, 122, 74)
            , 1: cc.rect(0, 0, 134, 62)
            , 2: cc.rect(0, 0, 122, 73)
            , 3: cc.rect(0, 0, 134, 62)
        }
        , ltqpCapInsets: {
            0: cc.rect(44, 20, 46, 22)//cc.rect(40, 40, 41, 14)
            , 1: cc.rect(44, 20, 46, 22)
            , 2: cc.rect(44, 20, 46, 22)
            , 3: cc.rect(44, 20, 46, 22)
        }
        , ltqpEmojiPos: {
            0: cc.p(45, -100)
            , 1: cc.p(-70, -28)
            , 2: cc.p(150, 28)
            , 3: cc.p(150, 28)
        }
        , ltqpVoicePos: {
            // 0: cc.p(40, 30)
            // , 1: cc.p(40, 30)
            // , 2: cc.p(30, 38)
            // , 3: cc.p(32, 30)
            0: cc.p(42, 32)
            , 1: cc.p(45, 32)
            , 2: cc.p(42, 32)
            , 3: cc.p(45, 32)
        }
        , ltqpEmojiSize: {
            0: cc.size(80, 64)
            , 1: cc.size(90, 52)
            , 2: cc.size(84, 64)
            , 3: cc.p(90, 52)
        }
        , ltqpTextDelta: {
            0: cc.p(4, -5)
            , 1: cc.p(-5, 0)
            , 2: cc.p(4, 5)
            , 3: cc.p(-5, 0)
        }
        , gPaiPos: {
            0: {1: 0, 2: 1, 3: 2},
            1: {0: 2, 2: 0, 3: 1},
            2: {0: 1, 3: 0, 1: 2},
            3: {0: 0, 1: 1, 2: 2}
        }
    };

    var data;
    var isReconnect;

    var roomState = null;
    var mapId = 2;
    var playerNum = 4;
    var rowBegin = 1;

    var enableChupaiCnt = 0;

    var isCCSLoadFinished = false;

    var uid2position = {};
    var uid2playerInfo = {};
    var position2uid = {};
    var position2sex = {};
    var position2playerArrIdx = {};

    var hasChupai = false;

    var turnRow = null;

    var isReplay = null;

    var forRows = null;

    var lianging = false;

    var liangPai = 0;
    var liangPaiIdx = 0;
    var liangStep = 0;

    var hideGangStep = 0;
    var hideGangArr = [];
    var hidedGangArr = [];
    var hideGangChupaiArr = [];

    var afterLianging = false;

    var disabledChuPaiIdMap = {};

    var disableChupai = false;

    var selectingXiaohu = false;

    var curHuPaiId = 0;

    // for wuhan
    var laiziPaiId = 0;
    var laizipiPaiAId = 0;
    var laizipiPaiBId = 0;

    var clearVars = function () {
        roomState = null;
        mapId = gameData.mapId;

        playerNum = gameData.playerNum || MAP2PNUM[gameData.appId] || 4;
        rowBegin = 1;
        isCCSLoadFinished = false;
        uid2position = {};
        uid2playerInfo = {};
        position2uid = {};
        position2sex = {};
        position2playerArrIdx = {};
        hasChupai = false;
        turnRow = null;
        isReplay = null;
        forRows = null;
        lianging = false;
        liangPai = 0;
        liangPaiIdx = 0;
        liangStep = 0;
        hideGangStep = 0;
        hideGangArr = [];
        hidedGangArr = [];
        hideGangChupaiArr = [];
        afterLianging = false;
        disabledChuPaiIdMap = {};
        disableChupai = false;
        selectingXiaohu = false;
        enableChupaiCnt = 0;

        laiziPaiId = 0;
        laizipiPaiAId = 0;
        laizipiPaiBId = 0;
    };

    var getPaiNameByRowAndId = function (row, id, isLittle, isStand) {
        var prefix;

        var ret = null;

        if (row == 0 && isLittle) prefix = 'p0s';
        if (row == 0 && !isLittle) prefix = 'p2l';
        if (row == 1 && isLittle) prefix = 'p1s';
        if (row == 1 && !isLittle) prefix = 'p2l';
        if (row == 2 && isLittle) prefix = 'p2s';
        if (row == 2 && !isLittle) prefix = 'p2l';
        if (row == 3 && isLittle) prefix = 'p3s';
        if (row == 3 && !isLittle) prefix = 'p2l';

        if (prefix) ret = prefix + id + '.png';

        if (row == 0 && id == 0 && isLittle) ret = 'p0s0' + '.png';
        if (row == 1 && id == 0 && isLittle) ret = 'p1s0' + '.png';
        if (row == 3 && id == 0 && isLittle) ret = 'p3s0' + '.png';
        if (row == 2 && id == 0 && !isLittle) ret = 'p2l0' + '.png';

        if (row == 0 && isStand && isLittle) ret = 'h0s' + '.png';
        if (row == 1 && isStand && isLittle) ret = 'h1s' + '.png';
        if (row == 3 && isStand && isLittle) ret = 'h3s' + '.png';
        if (row == 0 && isStand && !isLittle) ret = 'p2l0' + '.png';
        if (row == 1 && isStand && !isLittle) ret = 'by' + '.png';
        if (row == 3 && isStand && !isLittle) ret = 'bz' + '.png';

        return ret;
    };

    exports.Mahjong = cc.Layer.extendEX({
        chatLayer: null,
        chiLayer: null,
        settingLayer: null,
        throwDiceLayer: null,
        kaigangLayer: null,
        beforeOnCCSLoadFinish: null,
        afterGameStart: null,
        isIconMove: false,
        isTouchedSafeBtn: false,
        needBaojing: false,
        //4009总结数据
        RoomResultData : null,

        _clearView: function () {
            cc.log('_clearView');
            for (var i = 0; i < 4; i++) {
                safeHide($('info' + i + '.piao'));
                safeHide($('info' + i + '.offline'));
                safeHide($('info' + i + '.ok'));
                safeHide($('info' + i + '.ti'));
                safeHide($('info' + i + '.liang'));
                safeHide($('info' + i + '.zhuang'));
                // safeHide($('info' + i + '.qp'));
                safeHide($('info' + i + '.btn_invite'));
                safeHide($('info' + i + '.btn_zhunbei'));
            }
        },
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
            console.log('鹏涛重构过的服务器！');
        },

        onEnterTransitionDidFinish: function () {
            cc.Layer.prototype.onEnter.call(this);
            network.start();
        },

        /**
         * 显示测试
         * @private
         * */
        _showTest: function () {
            // showWindow('TestMahjong');
            this.addChild(new TestMahjong())
        },

        getRootNode: function () {
            return this.getChildByName('Scene');
        },
        initExtraMapData: function (data, is_Reconnect) {
            var that = this;
            laiziPaiId = data['laizi_id'];
            var laiziPanel = $('laizi_panel');
            if (laiziPanel) {
                laiziPanel.setVisible(true);
            }

            if ((mapId == MAP_ID_LEIYANG) && !is_Reconnect) {
                laiziPaiId = data['laizi_id'] || 32;
                if (!that.ishongzhongzuogui()) {
                    var zhainiaoLayer = new ZhaniaoLayer({pai_arr: [laiziPaiId], moveTo: [248, 640]}, 2);
                    this.addChild(zhainiaoLayer, 0);
                    this.playguipaiAnim(2);
                }
                setTimeout(function () {
                    var laiziPanel = $('laizi_panel');
                    if (laiziPanel) {
                        laiziPanel.setVisible(true);
                        that.showGuiPanel();
                        var pai = $('laizi_panel.fanpai_bg.pai');
                        var paiName = getPaiNameByRowAndId(2, laiziPaiId, true, false);
                        setSpriteFrameByName(pai, paiName, that.getPaiPlist());
                    }
                }, that.ishongzhongzuogui()
                   ? 0
                   : 2000);
            } else if (mapId == MAP_ID_ZHUANZHUAN) {
                var laiziPanel = $('laizi_panel');
                laiziPanel.setVisible(false);
            } else {
                var laiziPanel = $('laizi_panel');
                if (laiziPanel) {
                    if (!laiziPaiId) {
                        laiziPanel.setVisible(false);
                        return;
                    }
                    laiziPanel.setVisible(true);
                    var pai = $('laizi_panel.fanpai_bg.pai');
                    this.showGuiPanel();
                    var paiName = getPaiNameByRowAndId(2, laiziPaiId, true, false);
                    setSpriteFrameByName(pai, paiName, that.getPaiPlist());
                }

            }
        },
        /**
         * 更换水印
         */
        showLogo: function () {
            var logNode = $('logo');
            // if (mapId == MAP_ID_LEIYANG) {
            //     logNode.setTexture(cc.textureCache.addImage(res['logoleiyanggui.png']));
            // }
            // else if (mapId == MAP_ID_LEIYANGHONGZHONG) {
            //     logNode.setTexture(cc.textureCache.addImage(res['logohongzhong.png']));
            // }
            logNode.setVisible(true);
        },
        onCCSLoadFinish: function () {
            var that = this;

            addCachedCCSChildrenTo(majiang.res.MaScene1_json, this);
            batchSetChildrenZorder(this.getRootNode(), {
                info0: 1, info1: 1, info2: 1, info3: 1,
                info_n0: 2, info_n1: 2, info_n2: 20, info_n3: 2,
                row2: 10,
                cpghg: 12,
                btn_mic: 30,
                setting: 31, chat: 31, jiesan: 31, btn_control_btns: 32, jiesuan_btn_bg: 32,
                btn_zhunbei: 33, btn_jixuyouxi: 33, btn_chakanjiesuan: 33,
                btn_gengduo : 35,gengduo_bg : 35//留一个深度34给点击空白区域的layer
                //hu_type_layer: 99
            });

            $ = create$(this.getRootNode());

            this.getPai = this.getPai();
            this.getGPai = this.getGPai();
            this.addUsedPai = this.addUsedPai();
            this.countDown = this.countDown();

            this.calcPosConf();
            this._clearView();
            MicLayer.init($('btn_mic'), this);
            $('btn_mic').setPositionX( $('btn_mic').getPositionX()+cWidth);
            
            // EFFECT_EMOJI.init(this, $);
            if (isReconnect) {
                gameData.zhuangUid = data['zhuang_uid'];
                gameData.lianzhuang = data['lianzhuang'];
                gameData.left_round = data['curRound'] + 1 || 0;
                gameData.players = data['players'];
                gameData.wanfaDesp = data['desp'];
                if (cc.isUndefined(gameData.wanfaDesp)) {
                    var options = data['options'];
                    gameData.wanfaDesp = options['desp'];
                }
                if (gameData.wanfaDesp.indexOf('8局') >= 0) {
                    gameData.totalRound = 8;
                    gameData.left_round = gameData.totalRound - gameData.left_round;
                } else if (gameData.wanfaDesp.indexOf('16局') >= 0) {
                    gameData.totalRound = 16;
                    gameData.left_round = gameData.totalRound - gameData.left_round;
                } else {
                    gameData.totalRound = 8;
                    gameData.left_round = gameData.totalRound - gameData.left_round;
                }

                this._refreshRoundAndPai();
                this._refreshRoomState(data['room_status'] || majiang.RoomState.ONGOING, isReconnect);
                this.initExtraMapData(data, true);
            } else {
                this._refreshRoomState(majiang.RoomState.CREATED);
            }

            this.safenode = $('safenode');
            if (window.inReview) {
                this.safenode.setVisible(false);
            }

            //this.showSafeTipLayer(false);
            for (var i = 1; i <= 3; i++) {
                var safe_line = $('safe_line' + i, this.safenode);
                safe_line.setOpacity(255);
                safe_line.setVisible(false);
            }

            this.clearTable4StartGame(isReconnect, isReconnect, data);

            this.startTime();

            this.startSignal();

            getVersion('zipai');

            safeHide($('btn_test'));
            if (!cc.sys.isNative) {
                safeShow($('btn_test'));
                TouchUtil.setOnclickListener($('btn_test'), this._showTest.bind(this));
            }

            //聊天自适
            $('chat').setPositionX( $('chat').getPositionX()+cWidth);
            TouchUtil.setOnclickListener($('chat'), function () {
                //
                // that.addChild(new ChatLayer);
                showWindow('ChatWindow');
            });

            // TouchUtil.setOnclickListener($('Panel_1'), function () {
            //     that.hideControlBtns();
            // })

            //定位自适
            $('safenode.safebtn').setPositionX( $('safenode.safebtn').getPositionX()+cWidth);
            //#region 点击更多按钮事件
            $('gengduo_bg').setPositionX( $('gengduo_bg').getPositionX()+cWidth);
            $('btn_gengduo').setPositionX( $('btn_gengduo').getPositionX()+cWidth);
            TouchUtil.setOnclickListener($('btn_gengduo'), function () {
                var bg_gengduo = $('gengduo_bg');
                var bg_gengduo_mask = $('bg_gengduo_mask');
                //检测更多layer mask
                var is_gengduo_mask_valid = cc.sys.isObjectValid(bg_gengduo_mask);

                //检测更多mask layer
                if (!is_gengduo_mask_valid){
                    bg_gengduo_mask = new cc.LayerColor(cc.color(0, 0, 0, 0), cc.winSize.width, cc.winSize.height);
                    bg_gengduo_mask.setName('bg_gengduo_mask');
                    bg_gengduo_mask.setVisible(false);
                    that.getRootNode().addChild(bg_gengduo_mask, bg_gengduo.getLocalZOrder() - 1);
                    cc.eventManager.addListener(cc.EventListener.create({
                        event: cc.EventListener.TOUCH_ONE_BY_ONE,
                        swallowTouches: false,
                        onTouchBegan: function (touch, event) {
                            if (is_gengduo_mask_valid) {
                                bg_gengduo_mask.setVisible(false);
                            }
                            bg_gengduo.setVisible(false)
                        },
                        onTouchMoved: function (touch, event) {

                        },
                        onTouchEnded: function (touch, event) {
                        }
                    }), bg_gengduo_mask);
                }

                //检测更多layer
                if (cc.sys.isObjectValid(bg_gengduo)){
                    var is_bg_gengduo_visible = bg_gengduo.isVisible();
                    bg_gengduo.setVisible(!is_bg_gengduo_visible);
                    if (is_bg_gengduo_visible){
                        bg_gengduo_mask.setVisible(true);
                    }
                    else {
                        bg_gengduo_mask.setVisible(false);
                    }
                }
                else {
                    bg_gengduo_mask.setVisible(false);
                }
            });

            //玩法
            TouchUtil.setOnclickListener($('gengduo_bg.btn_wanfa'), function () {

            });

            //桌面
            TouchUtil.setOnclickListener($('gengduo_bg.btn_zhuomian'), function() {
                (function () {
                    i++;
                    if (i > bgArr.length) {
                        i = 1;
                    }
                    that.changeBg(i - 1);
                    cc.sys.localStorage.setItem(i - 1, i - 1);
                })(i);
            }, {});

            //解散
            TouchUtil.setOnclickListener($('gengduo_bg.btn_tuichu'), function() {
                if (that._room_state == majiang.RoomState.CREATED){
                    if (window.inReview)
                        network.send(3003, {room_id: gameData.roomId});
                    else
                        showMessageBox('解散房间不扣房卡，是否确定解散？', function () {
                            // clearGameMWRoomId();
                            network.send(3003, {room_id: gameData.roomId});
                        }, null, false, false, true, true);
                }else {
                    showMessageBox('确定要申请解散房间吗？', function () {
                        // clearGameMWRoomId();
                        network.send(3009, {room_id: gameData.roomId, is_accept: 1});
                    }, null, true, false, true, true);
                }
            });

            //设置
            TouchUtil.setOnclickListener($('gengduo_bg.btn_shezhi'), function () {
                showWindow('SettingWindow',Setting_TYPE.Table_dou14);
            });
            //#endregion

            TouchUtil.setOnclickListener($('btn_zhunbei'), function () {
                network.send(3004, {room_id: gameData.roomId});
            });

            TouchUtil.setOnclickListener($('btn_jixuyouxi'), function () {
                network.send(3004, {room_id: gameData.roomId});
            });

            TouchUtil.setOnclickListener($('img_dengdaijiaru'), function () {
                network.send(3004, {room_id: gameData.roomId});
            });

            TouchUtil.setOnclickListener($('btn_yxks'), function () {
                network.send(3004, {room_id: gameData.roomId});
            });

            TouchUtil.setOnclickListener($('btn_chakanjiesuan'), function () {
                if (that._jiesuan_data) {
                    that._openJiesuanLayer();
                }
            });

            TouchUtil.setOnclickListener($('btn_invite'), function () {
                ShareUtil.ShareRoomId(gameData.roomId, gameData.wanfaDesp, gameData.playerNum, gameData.players.length);
            });

            TouchUtil.setOnclickListener($('btn_copyinfo'), function () {
                var parts = decodeURIComponent(gameData.wanfaDesp).split(',');
                var mapName = parts[1];
                parts.splice(1, 1);
                var shareText = '【永州扯胡子】\n' + mapName + '\n房号: ' + ToDBC(gameData.roomId) + '\n'
                    + (parts.length
                       ? parts.join(', ') + ', '
                       : '') + '速度来啊！';
                savePasteBoard(shareText);
                that.showToast('复制成功');
            });

            TouchUtil.setOnclickListener($('btn_fanhui'), function () {
                if (gameData.club_id && gameData.ownerUid == gameData.uid) { // 群主
                    showMessageBox('确定要退出房间吗?', function () {
                        // clearGameMWRoomId();
                        network.send(3003, {room_id: gameData.roomId, leaveOnly: true});
                    }, null, false, true, true);
                } else {
                    if (gameData.uid != gameData.ownerUid) {
                        showMessageBox('确定要退出房间吗?', function () {
                            // clearGameMWRoomId();
                            network.send(3003, {room_id: gameData.roomId});
                        }, null, false, true, true);
                    }
                }
            });

            TouchUtil.setOnclickListener($('btn_jiesan'), function () {
                if (window.inReview)
                    network.send(3003, {room_id: gameData.roomId});
                else
                    showMessageBox('解散房间不扣房卡，是否确定解散？', function () {
                        // clearGameMWRoomId();
                        network.send(3003, {room_id: gameData.roomId});
                    }, null, false, false, true, true);
            });
            TouchUtil.setOnclickListener($('btn_tuichux'), function () {
                if (window.inReview)
                    network.send(3003, {room_id: gameData.roomId});
                else
                    showMessageBox('解散房间不扣房卡，是否确定解散？', function () {
                        // clearGameMWRoomId();
                        network.send(3003, {room_id: gameData.roomId});
                    }, null, false, false, true, true);
            });

            TouchUtil.setOnclickListener($('info0.head_bg'), function () {
                that.showPlayerInfoPanel(0);
            });
            TouchUtil.setOnclickListener($('info1.head_bg'), function () {
                that.showPlayerInfoPanel(1);
            });
            TouchUtil.setOnclickListener($('info2.head_bg'), function () {
                that.showPlayerInfoPanel(2);
            });
            TouchUtil.setOnclickListener($('info3.head_bg'), function () {
                that.showPlayerInfoPanel(3);
            });

            TouchUtil.setOnclickListener($('info0.ti'), function () {
                that.tiAlert(position2uid[0]);
            });
            TouchUtil.setOnclickListener($('info1.ti'), function () {
                that.tiAlert(position2uid[1]);
            });
            TouchUtil.setOnclickListener($('info2.ti'), function () {
            });
            TouchUtil.setOnclickListener($('info3.ti'), function () {
                that.tiAlert(position2uid[3]);
            });

            //进入房间，包括自己和其他玩家进入房间
            this.addCustomListener(3002, function (data) {
                gameData.last3002 = data;
                gameData.playerNum = data['max_player_cnt'];
                if (isReplay) {
                    mapId = data['map_id'];
                    gameData.mapId = data['map_id'];
                    gameData.wanfaDesp = data['desp'];
                }
                if (that.getRoomState() == ROOM_STATE_CREATED) {
                    gameData.ownerUid = data['owner'];
                    gameData.players = data['players'];
                    that.onPlayerEnterExit();
                }
                // clearGameMWRoomId();
            });
            //房间解散，被踢出房间，有玩家主动退出房间
            this.addCustomListener(3003, function (data) {
                // clearGameMWRoomId();
                var uid = data['uid'];
                if (data['room_id'] != gameData.roomId) {
                    return;
                }
                if (uid == gameData.uid) {
                    gameData.roomId = 0;
                    showBoard('HallBoard');
                    if (data['is_kick']) {
                        setTimeout(
                            function () {
                                showAlert('您被【' + uid2playerInfo[gameData.ownerUid].nickname + '】踢出房间');
                            }, 100
                        );
                    }
                    return;
                }
                if (data['is_kick']) {
                    if (gameData.uid != gameData.ownerUid) {
                        setTimeout(
                            function () {
                                showAlert('【' + uid2playerInfo[uid].nickname + '】被【' + uid2playerInfo[gameData.ownerUid].nickname + '】踢出房间');
                            }, 100
                        );
                    }
                }
                if (that.getRoomState() == ROOM_STATE_ONGOING)
                    return;
                if (data['del_room']) {
                    var owner = uid2playerInfo[gameData.ownerUid];
                    var tip = '';
                    if (undefined == owner) {
                        owner = {};
                        owner.nickname = '房主';
                        tip = owner.nickname + '已解散房间';
                    } else {
                        tip = owner.nickname + '已解散房间';
                    }
                    showMessageBox(tip, function () {
                        gameData.roomId = 0;
                        owner = null;
                        tip = null;
                        showBoard('HallBoard');
                    });
                }
                else {
                    var uid = data['uid'];
                    _.remove(gameData.players, function (player) {
                        return player.uid == uid;
                    });
                    that.onPlayerEnterExit();
                }
            });
            //准备
            this.addCustomListener(3004, function (data) {
                // if (that.getRoomState() != ROOM_STATE_ENDED)
                //     return;
                if (!data) {
                    return;
                }
                var uid = data['uid'];
                that.setReady(uid);
            });
            //房卡数有变动
            this.addCustomListener(3013, function (data) {
                gameData.numOfCards = data['numof_cards'];
            });
            // this.addCustomListener(3005, function (data) {
            // });
            //聊天
            this.addCustomListener(3008, function (data) {
                var uid = data['uid'];
                var type = data['type'];
                var voice = data['voice'];
                var content = decodeURIComponent(data['content']);
                that.showChat(uid2position[uid], type, content, voice, uid);
            });
            //请求房间解散的反馈信息
            this.addCustomListener(3009, function (data,errorCode) {
                if (errorCode == -1) {
                    showAlert("长时间未开始,房间自动解散");
                    return
                }
                if (data["arr"] == null || data["arr"] == undefined || data["arr"] == '' || (data["arr"] && data["arr"].length == 0)) {
                    return;
                }
                var that = this;
                var arr = data['arr'];
                var leftSeconds = data['left_sec'];
                leftSeconds = (leftSeconds < 0 ? 0 : leftSeconds);
                var byUserId = data['arr'][0].uid;
                if (that.isJiesan)
                    return;
                that.isJiesan = data['is_jiesan'];

                if (!that.RoomQuitWindow) {
                    that.RoomQuitWindow = showWindow('RoomQuitWindow', leftSeconds, arr, byUserId, data);
                } else {
                    that.RoomQuitWindow.setData(leftSeconds, arr, byUserId, data);
                }
                that.RoomQuitWindow.setVisible(true);

            });
            //信息公告
            // this.addCustomListener(3200, (function () {
            //     var interval = null;
            //     return function (data) {
            //         if (interval) {
            //             clearInterval(interval);
            //             interval = null;
            //         }
            //
            //         var content = decodeURIComponent(data['content']);
            //         var duration = (content.length * 0.3 <= 10) ? 10 : content.length * 0.3;
            //         var totalDuration = (0.2 + duration + 0.3 + 2) * 1000;
            //
            //         var func = function () {
            //             if (!that || !cc.sys.isObjectValid(that)) {
            //                 if (interval) {
            //                     clearInterval(interval);
            //                     interval = null;
            //                 }
            //                 return;
            //             }
            //             var speaker = $('speaker');
            //             var speakerPanel = $('speaker.panel');
            //             speaker.setLocalZOrder(100);
            //             speaker.runAction(cc.fadeIn(0.2));
            //             var text = new ccui.Text();
            //             text.setFontSize(26);
            //             text.setColor(cc.color(254, 245, 92));
            //             text.setAnchorPoint(cc.p(0, 0));
            //             text.enableOutline(cc.color(0, 0, 0), 1);
            //             speakerPanel.removeAllChildren();
            //             speakerPanel.addChild(text);
            //             text.setString(window.inReview ? "欢迎来到衡阳字牌!" : content);
            //             text.setPositionX(speakerPanel.getContentSize().width);
            //             text.setPositionY((speakerPanel.getContentSize().height - text.getContentSize().height) / 2);
            //             text.runAction(cc.sequence(
            //                 cc.delayTime(0.2)
            //                 , cc.moveTo(duration, -text.getVirtualRendererSize().width, 0)
            //                 , cc.delayTime(0.3)
            //                 // , cc.callFunc(function () { speaker.runAction(cc.fadeOut(0.2)) })
            //             ));
            //         };
            //         func();
            //         interval = setInterval(func, totalDuration);
            //     }
            // })());
            //轮到谁出牌指示
            this.addCustomListener(4000, function (data) {
                var uid = data['uid'];
                that.throwTurn(uid2position[uid]);
            });

            //摸牌
            this.addCustomListener(4001, function (data) {
                var uid = data['uid'];
                var paiId = data['pai_id'];
                var paiArr = data['pai_arr'];
                var liangPaiArr = data['liang_pai_arr'];
                gameData.left_pai_num = data['left'];
                that._refreshRoundAndPai();
                that.mopai(uid2position[uid], paiId, paiArr, liangPaiArr);
            });

            //出牌
            this.addCustomListener(4002, function (data) {
                var uid = data['uid'];
                var idx = data['idx'];
                var paiId = data['pai_id'];
                var paiArr = (data['pai_arr'] || []);
                var liangPaiArr = (data['liang_pai_arr'] || []);
                var paiCnt = (data['pai_cnt'] || 0);
                var left = (data['left'] || 0);
                var row = uid2position[uid];
                for (var i = 0; i < paiCnt; i++)
                    paiArr.push(0);
                that.chuPai(row, idx, paiId, paiArr, liangPaiArr);
            });
            // 其他玩家吃碰杠胡过
            this.addCustomListener(4003, function (data) {
                var uid = data['uid'];
                var fromUid = data['from_uid'];
                var paiId = data['pai_id'];
                var op = data['op'];
                var chi = op[0];
                var peng = op[1];
                var gang = op[2];
                var hu = op[3];
                if (chi) that.chiPengGangHu(OP_CHI, uid2position[uid], paiId, uid2position[fromUid], data);
                if (peng) that.chiPengGangHu(OP_PENG, uid2position[uid], paiId, uid2position[fromUid], data);
                if (gang) that.chiPengGangHu(OP_GANG, uid2position[uid], paiId, uid2position[fromUid], data);
                if (hu) {
                    that.chiPengGangHu(OP_HU, uid2position[uid], paiId, uid2position[fromUid], data);
                }
                if (!chi && !peng && !gang && !hu)
                    that.chiPengGangHu(OP_PASS, uid2position[uid], paiId, uid2position[fromUid], data);
            });
            // 自己能吃碰杠胡
            this.addCustomListener(4004, function (data) {
                var uid = data['uid'];
                var paiId = data['pai_id'];
                var op = data['op'];
                var row = uid2position[uid];
                that.showChiPengGangHu(row, paiId, op[0], op[1], op[2], op[3], op[4], data);
            });

            this.addCustomListener(4005, this._onChiPengGangHuTing.bind(this));

            this.addCustomListener(40044, function (data) {
                var arr = data['arr'];
                for (var i = 0; i < arr.length; i++) {
                    var uid = arr[i]['data']['uid'];
                    var paiId = arr[i]['data']['pai_id'];
                    var op = arr[i]['data']['op'];
                    var row = uid2position[uid];
                    that.showChiPengGangHu(row, paiId, op[0], op[1], op[2], op[3], op[4], data);
                }
            });

            // 结算
            this.addCustomListener(4008, function (data) {
                that._jiesuan_data = deepCopy(data);
                that._laiziPaiArr = [];
                that._refreshRoomState(majiang.RoomState.ENDED);
                var other_info = data['other_info'];
                that.jiesuan(data);
                if (other_info['zhuama_info']) {
                    that.addChild(new ZhuaMaLayer(other_info['zhuama_info'],that));
                } else {
                    that._openJiesuanLayer();
                }
                if (!isReplay) {
                    $('timer').setVisible(true);
                    //$('timer2').setVisible(true);
                    $('timer2x').setVisible(true);
                }
                that.setHuTipVisible(false);
            });

            cc.eventManager.addCustomListener('onExit_ZhuaMaLayer', this._openJiesuanLayer.bind(this));

            // 总结算
            this.addCustomListener(4009, function (data) {
                $('jiesuan_btn_bg').setVisible(false);
                $('btn_zhunbei').setVisible(false);
                $('img_dengdaijiaru').setVisible(false);
                $('btn_chakanjiesuan').setVisible(false);
                that.RoomResultData = data;
                //that.zongJiesuan(data);
            });

            //祝贺语
            this.addCustomListener(4010, function (data) {
                var msg = data.msg;
                that.showToast(decodeURIComponent(msg));
            });
            this.addCustomListener(4011, function (data) {
            });
            this.addCustomListener(4012, function (data) {
            });
            this.addCustomListener(4013, function (data) {
                that.showTip('第一步, 请选择一张要打出的牌');
                that.setPaiArrOfRow(2, data['pai_arr'], false, false, data['liang_pai_arr']);
                liangStep = 1;
            });
            this.addCustomListener(4014, function (data) {
                var paiArr = data['pai_arr'];
                var paiArrBak = _.clone(data['pai_arr']);
                var gangPaiArr = data['gang_pai_arr'];
                if (!gangPaiArr) {

                }
                else {
                    that.showTip('请选择不想显示的杠牌');
                    $('btn_xuanzewancheng').setVisible(true);
                    TouchUtil.setOnclickListener($('btn_xuanzewancheng'), function () {
                        that.selectHideGangCb.call(that);
                    });
                    for (var i = 0; i < gangPaiArr.length; i++) {
                        while (true) {
                            var j = paiArrBak.indexOf(gangPaiArr[i]);
                            if (j < 0)
                                break;
                            paiArrBak.splice(j, 1);
                        }
                    }
                    hideGangArr = gangPaiArr;
                    hidedGangArr = [];

                    if (gangPaiArr.length == 0)
                        that.selectHideGangCb();
                    else {
                        hideGangStep = 1;
                        that.setPaiArrOfRow(2, paiArr, false, false, gangPaiArr, true);
                    }
                }
                if (gameData.huTipData) {
                    that.showTishiTip(gameData.huTipData);
                    // console.log("111");
                }
            });
            this.addCustomListener(4015, function (data) {
                hideGangChupaiArr = data['ting_pai_arr'];
                hideGangStep = 2;
                that.showTip('请出一张牌');
                var paiArr = that.getPaiArr();
                that.setPaiArrOfRow(2, paiArr, false, false, hideGangChupaiArr);
                if ($('btn_xuanzewancheng')) {
                    $('btn_xuanzewancheng').setVisible(false);
                }
                if (gameData.huTipData) {
                    that.showTishiTip(gameData.huTipData);
                }
            });
            //玩家在线状态改变
            this.addCustomListener(4020, function (data) {
                var uid = data['uid'];
                var isOffline = data['is_offline'];
                that.playerOnloneStatusChange(uid2position[uid], isOffline);
            });
            //继续玩，下一局开局
            this.addCustomListener(4200, function (data) {
                that._hideReady();
                var clubTablesLayer = that.getChildByName('clubTablesLayer');
                if (clubTablesLayer) {
                    clubTablesLayer.removeFromParent(true);
                }
                that.setUpGameStartAnimation();
                var paiArr = data['paiArr'];
                var zhuangUid = data['zhuang_uid'];
                that._laiziPaiArr = data['laiziPaiArr'] || [];
                gameData.zhuangUid = zhuangUid;
                gameData.left_round = data['left_round'];
                gameData.totalRound = data['total_round'];
                gameData.curRound = data['cur_round'];
                that._refreshRoundAndPai();
                that.hideGuiPanel();
                that.initExtraMapData(data, false);

                that._refreshRoomState(majiang.RoomState.ONGOING);
                that.clearTable4StartGame(true);
                that.fapai(paiArr);
                that.setZhuang(uid2position[zhuangUid]);

                if (that.afterGameStart)
                    that.afterGameStart();
            });
            this.addCustomListener(4030, function (data, errCode) {
                if (errCode == -1) {
                    that.showTip('您选择要亮的或要出的牌不正确,请重新选择');
                    $('btn_queding').setVisible(true);
                    //$('btn_quxiao').setVisible(true);
                }
                else {
                    var uid = data['uid'];
                    that.hideTip();
                    var paiArr = data['pai_arr'];
                    var liangPaiArr = data['liang_pai_arr'] || [];

                    var row = uid2position[uid];
                    if (row == 2) {
                        afterLianging = true;
                        that.upPai(2, -1);
                    }
                    else {
                        for (var i = 0; i < paiArr.length; i++)
                            paiArr[i] = 0;
                    }

                    for (var i = 0; i < liangPaiArr.length; i++)
                        disabledChuPaiIdMap[liangPaiArr[i]] = true;

                    that.setPaiArrOfRow(row, paiArr, (row != 2), (row != 2), liangPaiArr);

                    if (row == 2) {
                        hasChupai = true;
                        that.hideTip();
                    }
                }
            });
            this.addCustomListener(4031, function (data, errCode) {
                if (errCode == -1) {
                    that.showTip('您选择要出的牌不正确,请重新选择');
                    //$('btn_xuanzewancheng').setVisible(true);
                    //$('btn_quxiao').setVisible(true);
                }
                else {
                    var uid = data['uid'];
                    that.hideTip();
                    var paiArr = data['pai_arr'];
                    var hidedGangPaiArr = data['hided_gang_arr'] || [];

                    var row = uid2position[uid];
                    if (row == 2) {
                        afterLianging = true;
                        that.upPai(2, -1);
                    }
                    else {
                        for (var j = 0; j < hidedGangPaiArr.length; j++) {
                            for (var i = 0; i < 4; i++) {
                                that.getGPai(row, i, 0);
                                var g = $('row' + row + '.g' + i);
                                if (g.isVisible() == false) {
                                    that.setGHide(row, i);
                                    g.setVisible(true);
                                    that.recalcPos(row);
                                    break;
                                }
                            }
                        }
                    }

                    //that.setPaiArrOfRow(row, paiArr, (row != 2), (row != 2), []);

                    if (row == 2) {
                        hasChupai = true;
                        that.hideTip();
                    }

                    if ($('info' + row + '.liang'))
                        $('info' + row + '.liang').setVisible(true);
                    setTimeout(function () {
                        that.playChiPengGangHuAnim(row, OP_LIANG);
                        playEffect('vliang', position2sex[row]);
                    }, 1200);
                }
            });
            this.addCustomListener(4041, function (data, errCode) {
            });
            this.addCustomListener(4050, function (data) {
                var arr = data['arr'];
                var haidiUid = data['haidi_uid'] || 0;
                var paiId = data['pai_id'] || 0;
                var allNo = true;
                for (var i = 0; i < arr.length; i++)
                    if (arr[i].val >= 0)
                        allNo = false;
                if (haidiUid) {
                    var haidiLayer = $('haidiLayer', that);
                    if (haidiLayer)
                        haidiLayer.removeFromParent(true);
                    showMessageBox('玩家【' + gameData.playerMap[haidiUid].nickname + '】获得海底牌: ' + PAINAMES[paiId], function () {
                    });
                }
                else if (allNo) {
                    var haidiLayer = $('haidiLayer', that);
                    if (haidiLayer)
                        haidiLayer.removeFromParent(true);
                    showMessageBox('没有玩家要海底牌');
                }
                else {
                    var haidiLayer = $('haidiLayer', that);
                    if (!haidiLayer) {
                        haidiLayer = new HaidiLayer();
                        haidiLayer.setName('haidiLayer');
                        that.addChild(haidiLayer);
                    }
                    haidiLayer.setArr(arr);
                }
            });
            //开杠
            this.addCustomListener(4052, function (data) {
                network.stop();
                var uid = data['uid'];
                var row = uid2position[uid];
                if (row == 2)
                    afterLianging = true;

                if ($('info' + row + '.liang'))
                    $('info' + row + '.liang').setVisible(true);
                if (row == 2) {
                    that.setPaiArrOfRow(2, that.getPaiArr(), false, false, []);
                    that.getPai(2, 13).setVisible(false);
                }
                var isReconnect = data['is_reconnect'] || false;
                var paiID = data['pai'];
                var paiIDA = data['pai_a'];
                var paiIDB = data['pai_b'];
                var paiStr = PAINAMES[paiIDA] + (paiIDB
                                                 ? ',' + PAINAMES[paiIDB]
                                                 : '');

                that.showTip('开杠: ' + paiStr);

                that.hideChiPengGangHu();

                var throwDiceCb = function () {
                    network.start();
                    var content = '玩家【' + ellipsisStr(_.trim(gameData.playerMap[uid].nickname), 6) + '】开杠' + PAINAMES[paiID] + ', 补牌: ' + paiStr + '\n请选择你可以进行的操作';

                    var qgh = data['qgh'];
                    var opA = data['op_a'];
                    var opB = data['op_b'];

                    if (opA[0] + opA[1] + opA[2] + opA[3] <= 0 &&
                        opB[0] + opB[1] + opB[2] + opB[3] <= 0 && !qgh)
                        return;

                    var layer = $('kaigangLayer', that) || that.kaigangLayer;
                    if (!layer) {
                        var scene = ccs.load(majiang.res.KaigangLayer_json);
                        layer = scene.node;
                        layer.setName('kaigangLayer');
                        layer.retain();
                        that.kaigangLayer = layer;
                    }
                    that.addChild(layer);

                    $('root.panel.lb_content', layer).setString(content);

                    var paiA = $('root.panel.a0', layer);
                    var paiB = $('root.panel.a1', layer);
                    paiA.setUserData({paiId: paiIDA});
                    paiB.setUserData({paiId: paiIDB});
                    setSpriteFrameByName(paiA, getPaiNameByRowAndId(2, paiIDA, true), that.getPaiPlist());
                    setSpriteFrameByName(paiB, getPaiNameByRowAndId(2, paiIDB, true), that.getPaiPlist());

                    var qghBtn = $('root.panel.btn_qgh', layer);
                    if (qgh) {
                        qghBtn.setVisible(true);
                        TouchUtil.setOnclickListener(qghBtn, function () {
                            network.send(4056, {room_id: gameData.roomId, pai_id: paiID, op: OP_HU});
                            layer.removeFromParent(false);
                        });
                    }
                    else {
                        qghBtn.setVisible(false);
                        TouchUtil.removeListeners(qghBtn);
                    }

                    var enableBtn = function (val, btn) {
                        if (val) {
                            Filter.remove(btn);
                            TouchUtil.setOnclickListener(btn, function () {
                                var op = btn.getName().split('_')[0];
                                var idx = btn.getName().split('_')[1];
                                op = {chi: 1, peng: 2, gang: 50, bu: 3, hu: 4, guo: 0}[op];
                                var pai = btn.getParent().getChildByName('a' + idx);
                                var _paiId = pai.getUserData().paiId;
                                if (op == 1) {
                                    that.showChiLayer(_paiId, function (paiId, oriPaiId) {
                                        network.send(4056, {
                                            room_id: gameData.roomId,
                                            pai_id: paiId,
                                            ori_pai_id: oriPaiId,
                                            op: op
                                        });
                                        layer.removeFromParent(false);
                                    });
                                }
                                else {
                                    network.send(4056, {room_id: gameData.roomId, pai_id: _paiId, op: op});
                                    layer.removeFromParent(false);
                                }
                                //console.log(op + ' ' + idx + ' ' + _paiId);
                            });
                        }
                        else {
                            Filter.grayScale(btn);
                            TouchUtil.removeListeners(btn);
                        }
                    };

                    enableBtn(opA[0], $('root.panel.chi_0', layer));
                    enableBtn(opA[1], $('root.panel.peng_0', layer));
                    enableBtn(opA[2], $('root.panel.gang_0', layer));
                    enableBtn(opA[2], $('root.panel.bu_0', layer));
                    enableBtn(opA[3], $('root.panel.hu_0', layer));

                    enableBtn(opB[0], $('root.panel.chi_1', layer));
                    enableBtn(opB[1], $('root.panel.peng_1', layer));
                    enableBtn(opB[2], $('root.panel.gang_1', layer));
                    enableBtn(opB[2], $('root.panel.bu_1', layer));
                    enableBtn(opB[3], $('root.panel.hu_1', layer));

                    TouchUtil.setOnclickListener($('root.panel.guo', layer), function () {
                        if (qgh) {
                            showMessageBox('当前可以抢杠胡, 确定要【过】吗? \n(点击取消可重新选择抢杠胡)', function () {
                                network.send(4056, {room_id: gameData.roomId, pai_id: 0, op: 0});
                                layer.removeFromParent(false);
                            });
                        }
                        else {
                            network.send(4056, {room_id: gameData.roomId, pai_id: 0, op: 0});
                            layer.removeFromParent(false);
                        }
                    });
                };

                if (isReconnect) {
                    network.start();
                    throwDiceCb();
                }
                else
                    that.throwDice('开杠摇骰子', data['dice'], paiIDA, paiIDB, throwDiceCb);
            });
            this.addCustomListener(4053, function (data) {
                that.showTip('请等待他人选择是否小胡');
                disableChupai = true;
                selectingXiaohu = true;
            });
            this.addCustomListener(4054, function (data) {
                that.hideTip();
                disableChupai = false;
                selectingXiaohu = false;
            });
            this.addCustomListener(4055, function (data) {
                that.hideTip();
                disableChupai = false;
                selectingXiaohu = false;

                var uid = data['uid'];
                var row = uid2position[uid];
                if (row != 2) {
                    var paiArr = data['pai_arr'];
                    var paiCnt = data['pai_cnt'];
                    var n = paiCnt - paiArr.length;
                    for (var i = 0; i < n; i++)
                        paiArr.push(0);
                    that.setPaiArrOfRow(row, paiArr, true, false);
                }

                that.playChiPengGangHuAnim(row, OP_HU, false);
                playEffect('vhu', position2sex[row]);

                var hu_type_arr = data['hu_type_arr'];
                if (hu_type_arr && hu_type_arr.length > 0) {
                    that.HuTypeAnimation(row, hu_type_arr);
                }
            });
            this.addCustomListener(4058, function (data) {
                var layer = ccs.load(majiang.res.KaigangReplayLayer_json).node;
                var content = $('root.lb_content', layer);
                content.setString(decodeURIComponent(data.content));
                that.addChild(layer);
                that.scheduleOnce(function () {
                    layer.removeFromParent(true);
                }, 5);
            });

            //听牌提示
            this.addCustomListener(4062, function (data) {
                that.showTishiTip(data);
            });

            //及时算分
            this.addCustomListener(4066, function (data) {
                // todo data格式recv: {"code":4066,"data":{"scores":[{"uid":11, "score":-100, "total":900}, {"uid":1897, "score":-100, "total":900}, {"uid":5059, "score":100, "total":1100}, {"uid":5060, "score":100, "total":1100}]}}
                if (data && data['scores']) {
                    var scores = data['scores'];
                    for (var i = 0; i < scores.length; i++) {
                        var row = uid2position[scores[i]['uid']];
                        that.showChangeScore(row, scores[i]['score']);
                        $('info' + row + '.lb_score').setString(scores[i]['total']);
                    }
                }
            });

            // 显示选飘
            this.addCustomListener(4100, this._onSelectedPiao.bind(this));

            // 选飘结果
            this.addCustomListener(4102, this._onPiao.bind(this));

            network.start();

            isCCSLoadFinished = true;

            playMusic();

            //静音按钮
            var nosound = cc.sys.localStorage.getItem('voiceFlag') == 1;
            gameData.voiceFlag = nosound;
            // $('noVoice').setTexture(gameData.voiceFlag
            //                         ? majiang.res.SelectJingYin
            //                         : majiang.res.JingYin);
            TouchUtil.setOnclickListener($('noVoice'), function () {
                showWindow('SettingWindow',Setting_TYPE.Table_dou14);
                // if (!cc.sys.isNative) return;
                // if (gameData.voiceFlag) {
                //     gameData.voiceFlag = false;
                //     jsb.AudioEngine.resumeAll();
                //     playMusic();
                // } else {
                //     gameData.voiceFlag = true;
                //     jsb.AudioEngine.pauseAll();
                // }
                // $('noVoice').setTexture(gameData.voiceFlag
                //                         ? majiang.res.SelectJingYin
                //                         : majiang.res.JingYin);
                // cc.sys.localStorage.setItem('voiceFlag', gameData.voiceFlag
                //                                          ? 1
                //                                          : 0);
            });
        },
        showPlayerInfoWinDow: function (playerInfo) {
            var self = this;
            network.send(3018, {cmd: 'queryEmoji',uid: gameData.uid,room_id:gameData.roomId});
            showWindow('PlayerInfoInGameWindow',playerInfo,self);
        },

        addCustomListener: function (type, func) {
            this.addListener(type, func);
        },
        addListener:function(code, listener){
            network.addListener(code, listener, this);
        },
        setupPlayers: function () {
            var that = this;
            if (mRoom.isReplay) {
                gameData.players = mRoom.replayData.users;
            }
            var data = gameData.players || [];
            var pos = 0;
            if (mRoom.isReplay == true) {
                pos = 0;
            } else {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].uid == gameData.uid) {
                        pos = i;
                    }
                }
            }
            this.pos0 = pos;
            this.pos1 = (pos + 1) % gameData.playerNum;
            this.pos2 = (pos + 2) % gameData.playerNum;
            this.pos3 = (pos + 3) % gameData.playerNum;

            //报警  100以内  报警
            that.needBaojing = false;
            // gameData.location = "0.1,0.1";
            for (var i = 0; i < data.length; i++) {
                if (data[i].uid != gameData.uid) {
                    var pos = that.getRowByUid(data[i].uid);
                    console.log(pos+"==="+data[i].NickName);
                    console.log("Location==="+data[i]['Location']);
                    this.addGpsTip(pos, data[i]['nickname'], data[i]['loc']);
                }
            }
            //任意两个人距离 <500 就报警
            for (var i = 0; i < data.length; i++) {
                for (var j = i + 1; j < data.length; j++) {
                    var distance = this.getJuliByLoc(data[i]['loc'], data[j]['loc']);
                    //console.log('============distance:'+distance);
                    if (distance <= 500) {
                        that.needBaojing = true;
                        break;
                    }
                }
            }
            // var safebtn = $("safebtn", that.safenode);
            // safebtn.setVisible(needBaojing);
            if (!window.inReview) {
                this.showSafeTipLayer(that.needBaojing);
            }

            var ORIENTATION2 = {};
            for (var i = 0; i < gameData.players.length; i++) {
                ORIENTATION2[uid2position[gameData.players[i].uid]] = ORIENTATION[gameData.players[i].pos];
            }
            for (var j = 0; j < 4; j++) {
                //$('timer.txt'+j).setString(ORIENTATION2[j]);
                $('timer.txt' + j).setVisible(false);
            }


        },

        getJuliByLoc: function (loc, loc2) {
            var distance = 100000;
            if (loc) {
                var templocation1 = loc.split(',');
                var otherpeoplelocationlat = 0;
                var otherpeoplelocationlng = 0;
                if (templocation1.length == 2) {
                    otherpeoplelocationlat = templocation1[1];
                    otherpeoplelocationlng = templocation1[0];
                }

                var mylocationlat = 0;
                var mylocationlng = 0;
                if (loc2) {
                    var templocation2 = loc2.split(',');
                    if (templocation2.length == 2) {
                        mylocationlat = templocation2[1];
                        mylocationlng = templocation2[0];
                    }
                }
                distance = getFlatternDistance(mylocationlat, mylocationlng, otherpeoplelocationlat, otherpeoplelocationlng);
            }
            return distance;
        },

        //GPS 提示
        showSafeTipLayer: function (_bool) {
            var visible = _bool;
            if (mRoom.isReplay) visible = false;
            var that = this;
            var safebtn = $('safebtn', that.safenode);
            var safe_gps = $('safebtn.safe_gps', that.safenode);
            var safe_gps2 = $('safebtn.safe_gps2', that.safenode);
            safe_gps.setVisible(true);
            safe_gps2.setVisible(true);
            if (_bool) {

                if (!that.isTouchedSafeBtn) {
                    safe_gps.runAction(cc.repeatForever(cc.sequence(cc.fadeIn(0.5), cc.fadeOut(0.5))));
                    safe_gps2.runAction(cc.repeatForever(cc.sequence(cc.fadeOut(0.5), cc.fadeIn(0.5))));
                } else {
                    safe_gps.setOpacity(255);
                    safe_gps2.setOpacity(255);
                    safe_gps.stopAllActions();
                    safe_gps2.stopAllActions();
                    safe_gps.setVisible(true);
                    safe_gps2.setVisible(false);
                }

            } else {
                safe_gps.setVisible(false);
                safe_gps2.setVisible(true);
            }

            TouchUtil.setOnclickListener(safebtn, function () {
                //var posArr = {pos0: that.pos0, pos1: that.pos1, pos2: that.pos2};
                that.isTouchedSafeBtn = true;
                safe_gps.setOpacity(255);
                safe_gps2.setOpacity(255);
                safe_gps.stopAllActions();
                safe_gps2.stopAllActions();
                if (that.needBaojing) {
                    safe_gps.setVisible(true);
                    safe_gps2.setVisible(false);
                }
                else {
                    safe_gps.setVisible(false);
                    safe_gps2.setVisible(true);
                }
                var posArr = {};
                if (gameData.players.length == 2) {
                    posArr = {pos0: that.pos0, pos1: that.pos1};
                }
                else if (gameData.players.length == 3) {
                    posArr = {pos0: that.pos0, pos1: that.pos1, pos2: that.pos2};
                }
                else if (gameData.players.length == 4) {
                    posArr = {pos0: that.pos0, pos1: that.pos1, pos2: that.pos2, pos3: that.pos3};
                }
                showWindow('PlayerInfoLocationWindow', false, that);
            });
        },

        //GPS 提示信息
        addGpsTip: function (pos, name, loc) {
            var that = this;
            // var loc = '0.000001,0.00001';
            // gameData.location = '0.000001,0.00001';
            //console.log(pos+"?????????????=="+name+"==");

            var safelayer = that.getChildByName('safelayer');
            if (safelayer) {
                var posArr = {pos0: this.pos0, pos1: this.pos1, pos2: this.pos2, pos3: this.pos3};
                safelayer.setPlayerJuli(posArr, playerNum);
            }
            if (loc == undefined || loc == null || loc == 'false' || loc == false) {
                return;
            }
            var templocation1 = loc.split(',');
            var otherpeoplelocationlat = 0;
            var otherpeoplelocationlng = 0;
            if (templocation1.length == 2) {
                otherpeoplelocationlat = templocation1[1];
                otherpeoplelocationlng = templocation1[0];
            }

            var mylocationlat = 0;
            var mylocationlng = 0;
            if (gameData.location && gameData.location.length > 0) {
                var templocation2 = gameData.location.split(',');
                if (templocation2.length == 2) {
                    mylocationlat = templocation2[1];
                    mylocationlng = templocation2[0];
                }
            }
            var juli = '';
            var distance = getFlatternDistance(mylocationlat, mylocationlng, otherpeoplelocationlat, otherpeoplelocationlng);
            if (distance <= 100) {
                juli = '玩家[' + name + ']' + '距您距离过近（' + distance + '米）';

                var safe_line = $('safe_line' + (pos + 1), this.safenode);
                if (safe_line) {
                    if (this.safenode.nodeNum == undefined || this.safenode.nodeNum == null) {
                        this.safenode.nodeNum = 0;
                    }
                    safe_line.setOpacity(255);
                    safe_line.setVisible(true);
                    if (!safe_line.pos) {
                        this.safenode.nodeNum += 1;
                        safe_line.setPositionY(safe_line.getPositionY() - (this.safenode.nodeNum) * 40);
                        // console.log(pos + "==="+ safe_line.getPositionY());
                    }
                    safe_line.pos = true;
                    var tip = safe_line.getChildByName('tip');
                    tip.setString(juli);
                    safe_line.runAction(cc.sequence(
                        cc.delayTime(15),
                        cc.fadeOut(1),
                        cc.callFunc(function () {
                            safe_line.pos = false;
                            safe_line.setVisible(false);
                            if (that.safenode.nodeNum > 0) that.safenode.nodeNum -= 1;
                        })
                    ));
                }
            }
        },
        HuTypeAnimation: function (row, arr) {
            var that = this;
            if (arr.length > 0) {
                var huType = arr.shift();
                var typeSprite = new cc.Sprite('res/table/hu_type/' + huType + '.png');
                $('info_n' + row).addChild(typeSprite);
                typeSprite.runAction(
                    cc.sequence(
                        cc.moveBy(1.2, cc.p(0, 150)).easing(cc.easeOut(2.0)),
                        cc.callFunc(function () {
                            typeSprite.removeFromParent(true);
                            that.HuTypeAnimation(row, arr);
                        })
                    )
                );
                $('hu_type_layer').setVisible(true);
            } else {
                $('hu_type_layer').setVisible(false);
            }
        },
        showTishiTip: function (data) {
            var that = this;
            // if (data == null || hasChupai) return;
            if (data == null) {
                return;
            }
            if (gameData.uid !== data.uid) {
                return;
            }
            gameData.huTipData = data;
            //胡牌提示
            for (var i = 0; i < 14; i++) {
                (function (i) {
                    var cardSprite = that.getPai(2, i);
                    var userData = cardSprite.getUserData();
                    var paiId = userData.pai;
                    var hucards = null;
                    for (var cards in data.tishi) {
                        if (parseInt(cards) == parseInt(paiId)) {
                            hucards = data.tishi[cards];
                            break;
                        }
                    }
                    var hucardSprite;
                    if (cardSprite.getChildByName('hucardSprite')) {
                        hucardSprite = cardSprite.getChildByName('hucardSprite');
                        hucardSprite.setPosition(cardSprite.getContentSize().width / 2 - 20.8, cardSprite.getContentSize().height - 38);
                    } else {
                        hucardSprite = new cc.Sprite(majiang.res.hupaitip_jiao_png);
                        hucardSprite.setPosition(cardSprite.getContentSize().width / 2 - 20.8, cardSprite.getContentSize().height - 38);
                        hucardSprite.setName('hucardSprite');
                        cardSprite.addChild(hucardSprite);
                    }
                    var duration = 2;
                    hucardSprite.setVisible(!!hucards);
                    // hucardSprite.runAction(new cc.RepeatForever(cc.sequence(
                    //     cc.spawn(cc.moveBy(duration, 0, 10), cc.fadeTo(duration, 188)),
                    //     cc.spawn(cc.moveBy(duration, 0, -10), cc.fadeTo(duration, 255))
                    // )));
                    var userData = cardSprite.getUserData();
                    userData.hucards = hucards;
                })(i);
            }
        },
        tiAlert: function (destUid) {
            showMessageBox('是否踢出【' + uid2playerInfo[destUid].nickname + '】该玩家？', function () {
                network.send(3010, {room_id: gameData.roomId, dest_uid: destUid});
            }, function () {
            });
        },
        onExit: function () {
            if (this.chatLayer)
                this.chatLayer.release();
            if (this.settingLayer)
                this.settingLayer.release();
            if (this.chiLayer)
                this.chiLayer.release();
            if (this.throwDiceLayer)
                this.throwDiceLayer.release();
            if (this.kaigangLayer)
                this.kaigangLayer.release();
            network.removeListenersForTarget(this);
            
            window.soundQueue = [];
            cc.Layer.prototype.onExit.call(this);
        },
        refreshPlayersStates: function () {
            if (this.assistantLayer && cc.sys.isObjectValid(this.assistantLayer)) {
                this.assistantLayer.refreshPlayersStates();
            }
        },
        onPlayerEnterExit: function () {
            var that = this;
            var players = gameData.players;
            for (var i = 0; i < players.length; i++) {
                var player = players[0];
                if (player.uid != gameData.uid) {
                    players.splice(0, 1);
                    players.push(player);
                }
                else
                    break;
            }
            //开始位置加
            that.refreshPlayersStates();
            $('timer').setUserData({delta: i});
            uid2position = {};
            for (var i = 0, j = 2; i < players.length; i++, j++) {
                var player = players[i];
                var k = {
                    4: {'0': 0, '1': 3, '2': 2, '3': 1},
                    3: {'0': 1, '1': 3, '2': 2},
                    2: {'0': 2, '1': 0}
                }[playerNum][j % playerNum];

                $('info' + k).setVisible(true);
                $('info' + k + '.lb_nickname').setString(ellipsisStr(player['nickname'], (k == 0 || k == 2
                                                                                          ? 7
                                                                                          : 5)));
                if (this._room_state === majiang.RoomState.CREATED) {
                    var is_ready = player['ready'] === 1;
                    $('info' + k + '.ok').setVisible(is_ready);
                    if (gameData.uid === player.uid) {
                        safeVisible($('btn_zhunbei'), !is_ready);
                    }
                }
                safeString($('info' + k + '.lb_score'), player['total_score']);

                if (k != 2 && gameData.uid == gameData.ownerUid && that.getRoomState() == ROOM_STATE_CREATED) {
                    $('info' + k + '.ti').setVisible(true);
                }
                loadImageToSprite(player['headimgurl'], $('info' + k + '.head'));
                uid2position[player.uid] = k;
                uid2playerInfo[player.uid] = player;
                position2uid[k] = player.uid;
                position2sex[k] = player.sex;
                position2playerArrIdx[k] = i;
            }

            for (; i < playerNum; i++, j++) {
                var k = {
                    4: {'0': 0, '1': 3, '2': 2, '3': 1},
                    3: {'0': 1, '1': 3, '2': 2},
                    2: {'0': 2, '1': 0}
                }[playerNum][j % playerNum];
                $('info' + k).setVisible(false);
            }

            if (playerNum == 3) {
                $('info0').setVisible(false);
                $('row1').y = 242; // todo 这里暂时写死
                $('row3').y = 135; // todo 这里暂时写死
            }

            if (playerNum == 2) {
                $('info1').setVisible(false);
                $('info3').setVisible(false);
            }

            if (gameData.uid == gameData.ownerUid) {
                if (players.length < playerNum) {
                    //$('btn_invite').setVisible(gameData.loginType != 'yk');
                    $('btn_yxks').setVisible(false);
                } else if (that.getRoomState() == ROOM_STATE_CREATED) {
                    //$('btn_invite').setVisible(false);
                    // $('btn_yxks').setVisible(gameData.loginType != 'yk');
                    $('btn_yxks').setVisible(false);
                }
            }
            if (isReplay) {
                $('btn_invite').setVisible(false);
            }

            eventManager.dispatchEvent(EventKey.ClubPlayerEnterExit, gameData.players);
            /*
            if (gameData.club_id && gameData.club_id > 0 && this.assistantLayer && that.getRoomState() == ROOM_STATE_CREATED && cc.sys.isObjectValid(this.assistantLayer)) {
                this.assistantLayer.setVisible(players.length != playerNum);
            }
             */

            that.setupPlayers();
        },
        calcPosConf: function () {
            if (gameData.posConf) {
                posConf = gameData.posConf;
                return;
            }
            for (var row = 0; row < 4; row++) {
                var a0 = $('row' + row + '.a0');
                posConf.paiA0PosBak[row] = a0.getPosition();
                posConf.paiA0ScaleBak[row] = [a0.getScaleX(), a0.getScaleY()];
                posConf.headPosBak[row] = $('info' + row).getPosition();

                if (row == 0 || row == 2) {
                    var a0 = $('row' + row + '.a0');
                    var a1 = $('row' + row + '.a1');
                    posConf.paiADistance.push(a1.getPositionX() - a0.getPositionX());
                    var b0 = $('row' + row + '.c0.b0');
                    var b1 = $('row' + row + '.c0.b1');
                    posConf.paiUsedDistance.push(b1.getPositionX() - b0.getPositionX());

                    posConf.downPaiPositionY = a0.getPositionY();
                    posConf.upPaiPositionY = a0.getPositionY() + UPPAI_Y;
                }
                else {
                    var a0 = $('row' + row + '.a0');
                    var a1 = $('row' + row + '.a1');
                    posConf.paiADistance.push(a1.getPositionY() - a0.getPositionY());
                    var b0 = $('row' + row + '.c0.b0');
                    var b1 = $('row' + row + '.c0.b1');
                    posConf.paiUsedDistance.push(b1.getPositionY() - b0.getPositionY());
                }

                var b0 = $('row' + row + '.g0.b0');
                var b2 = $('row' + row + '.g0.b2');

                if (row == 0) posConf.groupWidth[0] = b0.getPositionX() + b0.getContentSize().width / 2 - (b2.getPositionX() - b2.getContentSize().width / 2);
                if (row == 2) posConf.groupWidth[2] = b2.getPositionX() + b2.getContentSize().width / 2 - (b0.getPositionX() - b0.getContentSize().width / 2);
                if (row == 1) posConf.groupHeight[1] = b2.getPositionY() + b2.getContentSize().height / 2 - (b0.getPositionY() - b0.getContentSize().height / 2);
                if (row == 3) posConf.groupHeight[3] = b0.getPositionY() + b0.getContentSize().height / 2 - (b2.getPositionY() - b2.getContentSize().height / 2);

                // var ltqp = $('info' + row + '.qp');
                // posConf.ltqpPos[row] = ltqp.getPosition();
                // posConf.ltqpEmojiSize[row] = cc.size(posConf.ltqpRect[row].width, posConf.ltqpRect[row].height);//cc.size({0: 80, 1: 90, 2: 84, 3: 100}[row], posConf.ltqpRect[row].height);
            }
            gameData.posConf = posConf;
        },

        /**
         * 小结算数据
         * @private
         * */
        _jiesuan_data: null,

        /**
         * 癞子牌数组
         * @type {Array}
         * @private
         * */
        _laiziPaiArr: [],

        /**
         * 房间状态
         * @private
         * */
        _room_state: majiang.RoomState.NONE,

        /**
         * 胡牌类型(4005)
         * @private
         * */
        _huType: 0,
        setRoomData: function (_data, roomDataType) {
            isReplay = (roomDataType == ROOM_DATA_TYPE.REPLAY);
            isReconnect = (roomDataType == ROOM_DATA_TYPE.RECONNECT);
            data = (isReplay || isReconnect)?_data:null;
        },
        ctor: function (_data, _isReplay) {
            this._super();
            this._jiesuan_data = null;
            this._laiziPaiArr = [];
            this._room_state = majiang.RoomState.CREATED;

            cc.sys.localStorage.setItem(NOW_PAGE_STAGE.STAGE_CREATE_LAYER, 0);
            cc.sys.localStorage.setItem(NOW_PAGE_STAGE.STAGE_pokerCLUB_LAYER + '_btn_clubId', 0);
            cc.sys.localStorage.setItem(NOW_PAGE_STAGE.STAGE_CLUB_LAYER, 0);

            var paibeiid = cc.sys.localStorage.getItem('paibeiid') || 0;
            this.changePaibei(paibeiid);

            clearVars();

            var that = this;
            forRows = function (cb) {
                if (playerNum == 4 || playerNum == 2)
                    cb.call(that, 0);
                if (playerNum != 2)
                    cb.call(that, 1);
                cb.call(that, 2);
                if (playerNum != 2)
                    cb.call(that, 3);
            };

            // data = _data;
            this.setRoomData(_data, _isReplay);
            var node = loadCCSTo(majiang.res.MahjoingLayout_json, this, 'Scene');
            node.setAnchorPoint(cc.p(0.5, 0.5));
            node.setPosition(cc.p(cc.winSize.width / 2, cc.winSize.height / 2));

            var sceneid = cc.sys.localStorage.getItem('sceneid') || 0;
            this.changeBg(sceneid);

            return true;
        },
        changeBg: function (sceneid) {
            if (sceneid > 4) {
                sceneid = 0;
            }
            cc.sys.localStorage.setItem('sceneid', sceneid);
            $('bg').setTexture(majiang.resPath+'img/room/table_back' + sceneid + '.jpg');
        },
        changePaibei: function (paibeiid) {
            cc.spriteFrameCache.removeSpriteFramesFromFile(majiang.resPath+'pai.plist');
            cc.spriteFrameCache.removeSpriteFramesFromFile(majiang.resPath+'pai_p.plist');
            cc.spriteFrameCache.removeSpriteFramesFromFile(majiang.resPath+'pai_y.plist');
            cc.spriteFrameCache.addSpriteFrames(majiang.resPath+'pai.plist');
        },
        startSignal: function () {
            var that = this;
            var interval = null;
            var lastDealy = -1;
            var func = function () {
                if (!that || !cc.sys.isObjectValid(that))
                    return clearInterval(interval);
                var delay = network.getLastPingInterval();
                if (delay == lastDealy)
                    return;
                //console.log('delay ' + delay);
                lastDealy = delay;
                if (delay < 100) $('signal').setTexture(signal3);
                else if (delay < 200) $('signal').setTexture(signal3);
                else if (delay < 300) $('signal').setTexture(signal2);
                else if (delay < 600) $('signal').setTexture(signal2);
                else $('signal').setTexture(signal1);
            };
            func();
            interval = setInterval(func, 200);
        },
        startTime: function () {
            var interval = null;
            var flag = true;
            var lbTime = $('lb_time');
            if (isReplay) {
                safeHide(lbTime);
                return;
            }
            var updTime = function () {
                //显示电池电量
                var battery = $('battery');
                var level = DeviceUtil.getBatteryLevel();
                if (cc.sys.isObjectValid(battery)) {
                    if (level > 75) {
                        battery.setTexture(BatteryTextures['battery5']);
                    } else if (level > 50) {
                        battery.setTexture(BatteryTextures['battery4']);
                    } else if (level > 25) {
                        battery.setTexture(BatteryTextures['battery3']);
                    } else if (level > 10) {
                        battery.setTexture(BatteryTextures['battery2']);
                    } else {
                        battery.setTexture(BatteryTextures['battery1']);
                    }
                }
                var date = new Date();
                var minutes = (date.getMinutes() < 10
                               ? '0'
                               : '') + date.getMinutes();
                var hours = (date.getHours() < 10
                             ? '0'
                             : '') + date.getHours();
                if (cc.sys.isObjectValid(lbTime))
                    lbTime.setString(hours + (flag
                                              ? ':'
                                              : ' ') + minutes);
                else if (interval)
                    clearInterval(interval);
                flag = !flag;
            };
            updTime();
            interval = setInterval(updTime, 1000);
        },
        isMyTurn: function () {
            return turnRow == 2;
        },
        getTurn: function () {
            for (var i = 0; i < 4; i++) {
                var node = $('timer.' + i);
                if (node.isVisible())
                    return (i + $('timer').getUserData().delta) % 4;
            }
            return -1;
        },
        throwTurnByUid: function (uid) {
            this.throwTurn(uid2position[uid]);
        },
        throwTurn: function (row) {
            turnRow = row;

            $('timer').setVisible(true);
            //$('timer2').setVisible(true);
            $('timer2x').setVisible(true);
            var arrow = $('timer.arrow');
            arrow.setTexture(cc.textureCache.addImage(majiang.res['arrow_' + row]));
            arrow.setVisible(true);
            if (arrow.getNumberOfRunningActions() == 0)
                arrow.runAction(new cc.RepeatForever(cc.sequence(cc.fadeTo(0.5, 168), cc.fadeTo(0.5, 255))));

            if (!afterLianging) {
                for (var i = 0; i < 14; i++) {
                    var pai = this.getPai(2, i);
                    var userData = pai.getUserData();
                    if (row == 2/* && !disabledChuPaiIdMap[userData.pai]*/) {
                        userData.isLiang = true;
                        Filter.remove(pai);
                        if (userData.pai == laiziPaiId && this.isShaGui()) {//不杀鬼
                            userData.isLiang = false;
                            //console.log(userData.isLiang);
                            // Filter.grayMask(pai);
                        }
                    }
                    else {
                        userData.isLiang = false;
                        // Filter.grayMask(pai);
                    }
                }
            }

            if (row == 2)
                this.upPai(2, -1);
            this.hideTip();
            gameData.huTipData = null;
            if (mapId == MAP_ID_LEIYANG) {
                for (var k = 0; k < 14; k++) {
                    var pai = this.getPai(2, k);
                    if (row == 2 && (pai.getUserData().pai == laiziPaiId)) {
                        if (this.isShaGui()) {//不杀鬼
                            pai.getUserData().isLiang = false;
                            Filter.grayYellow(pai);
                        } else {
                            Filter.grayYellow(pai);
                        }
                    }

                }
            } else if (mapId == MAP_ID_LEIYANGHONGZHONG) {
                for (var k = 0; k < 14; k++) {
                    var pai = this.getPai(2, k);
                    if (row == 2 && (pai.getUserData().pai == laiziPaiId)) {
                        if (this.isShaGui()) {//不杀鬼
                            pai.getUserData().isLiang = false;
                            Filter.grayYellow(pai);
                        } else {
                            Filter.grayYellow(pai);
                        }
                    }

                }
            }
        },
        setPai: function (row, idx, val, isLittle, isStand, isVisible) {
            var pai = this.getPai(row, idx);

            // 癞子角标
            var lb_lai = pai.getChildByName('lb_lai');
            safeHide(lb_lai);
            if (this._laiziPaiArr.indexOf(val) >= 0) {
                if (row === 2) {
                    if (!cc.sys.isObjectValid(lb_lai)) {
                        lb_lai = new cc.Sprite(majiang.res.lb_lai_png);
                        lb_lai.setName('lb_lai');
                        pai.addChild(lb_lai);
                        lb_lai.setPosition(16, 20);
                    }
                    safeShow(lb_lai);
                }
            }

            var userData = pai.getUserData();
            var paiName = getPaiNameByRowAndId(row, val, isLittle, val > 0
                                                                   ? false
                                                                   : (isReplay || roomState == ROOM_STATE_ENDED
                                                                      ? false
                                                                      : isStand));
            userData.pai = val;
            setSpriteFrameByName(pai, paiName,this.getPaiPlist());
            if (!_.isUndefined(isVisible)) {
                if (isVisible) {
                    pai.setVisible(true);
                } else {
                    pai.setVisible(false);
                }
            }
            return pai;
        },
        getPai: function () {
            var cache = {};
            return function (row, id) {
                cache[row] = cache[row] || {};
                if (cache[row][id])
                    return cache[row][id];
                var node = $('row' + row + '.a' + id);
                if (!node) {
                    var a0 = $('row' + row + '.a0');
                    node = duplicateNode(a0, true);
                    if (row == 0 || row == 2) node.setPositionX(posConf.paiADistance[row] * id + a0.getPositionX());
                    if (row == 1 || row == 3) node.setPositionY(posConf.paiADistance[row] * id + a0.getPositionY());
                    node.setName('a' + id);
                    a0.getParent().addChild(node, (row == 1
                                                   ? -id
                                                   : 0));
                }
                var userData = node.getUserData();
                if (!userData)
                    userData = {};
                userData.idx = id;
                node.setUserData(userData);
                cache[row][id] = node;
                return node;
            };
        },
        getPaiId: function (row, id) {
            var userData = this.getPai(row, id).getUserData();
            return userData.pai;
        },
        setLabelOfPai: function (pai, val, row, isLittle, isKnockout) {
            var lb = pai.getChildByName('lb');
            var texture = null;
            if (val != laiziPaiId) {
                return;
            }
            texture = majiang.res.lb_gui_png;
            if (!lb) {
                lb = new cc.Sprite(majiang.res.lb_gui_png);
                lb.setAnchorPoint(0, 1);
                lb.setTexture(texture);
                lb.setName('lb');
                pai.addChild(lb);
                if (row == 0) {
                    lb.setPosition(60.85, 12.50);
                    lb.setRotation(180);
                    lb.setScaleX(0.8);
                }
                if (row == 1) {
                    lb.setPosition(4, 15.5);
                    lb.setRotation(-90);
                    lb.setScaleX(0.8);
                }
                if (row == 2) {
                    if (isKnockout) {//是否是已经打出的牌
                        lb.setPosition(2, 89);
                        lb.setScale(0.85, 0.9);
                    }
                    else {
                        lb.setPosition(2, 104.5);
                        lb.setScale(1);
                    }
                }
                if (row == 3) {
                    lb.setPosition(73, 62);
                    lb.setRotation(90);
                    lb.setScaleX(0.8);
                }

            }
            else {
                lb.setTexture(texture);
            }
            if (val == laiziPaiId) lb.setVisible(true);
        },
        setGChi: function (row, j, paiId, oriPaiId) {
            var a = 0, b = 0, c = 0;
            if (_.isArray(paiId)) {
                a = paiId[0];
                b = paiId[1];
                c = paiId[2];
            }
            else {
                if (paiId - 1 == oriPaiId) {
                    a = paiId;
                    b = paiId - 1;
                    c = paiId + 1;
                }
                if (paiId == oriPaiId) {
                    a = paiId - 1;
                    b = paiId;
                    c = paiId + 1;
                }
                if (paiId + 1 == oriPaiId) {
                    a = paiId - 1;
                    b = paiId + 1;
                    c = paiId;
                }
            }
            this.setGPai(row, j, 0, a);
            this.setGPai(row, j, 1, b);
            this.setGPai(row, j, 2, c);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(false);
            $('row' + row + '.g' + j).setVisible(true);
        },
        setGPai: function (row, g, idx, val) {
            var pai = this.getGPai(row, g, idx);
            var userData = pai.getUserData();
            var paiName = getPaiNameByRowAndId(row, val, true);
            userData.pai = val;
            setSpriteFrameByName(pai, paiName, this.getPaiPlist());
        },
        setGPeng: function (row, j, paiId) {
            for (var k = 0; k < 3; k++)
                this.setGPai(row, j, k, paiId);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(false);
            $('row' + row + '.g' + j).setVisible(true);
        },
        setGHide: function (row, j) {
            for (var k = 0; k < 3; k++)
                this.setGPai(row, j, k, 0);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(false);
            $('row' + row + '.g' + j).setVisible(true);
        },
        setGGang: function (row, j, upPaiId, downPaiId) {
            if (downPaiId == 0) {
                upPaiId = upPaiId;//row == 2?upPaiId:0;
            }
            this.setGPai(row, j, 3, upPaiId);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(true);
            for (var k = 0; k < 3; k++)
                this.setGPai(row, j, k, downPaiId);
            $('row' + row + '.g' + j).setVisible(true);
        },
        setGJiaGang: function (row, paiId) {
            for (var j = 0; j < 4; j++)
                if ($('row' + row + '.g' + j).isVisible() &&
                    this.getGPaiId(row, j, 0) == paiId &&
                    this.getGPaiId(row, j, 0) == this.getGPaiId(row, j, 1) &&
                    this.getGPaiId(row, j, 1) == this.getGPaiId(row, j, 2)) {
                    this.setGPai(row, j, 3, paiId);
                    this.getGPai(row, j, 3).setVisible(true);
                    break;
                }
        },
        getGPai: function () {
            var cache = {};
            return function (row, g, id) {
                cache[row] = cache[row] || {};
                cache[row][g] = cache[row][g] || {};
                if (cache[row][g][id])
                    return cache[row][g][id];
                var group0 = $('row' + row + '.g' + 0);
                var groupNode = $('row' + row + '.g' + g);
                if (!groupNode) {
                    groupNode = duplicateNode(group0,true);
                    if (row == 0 || row == 2) groupNode.setPositionX(group0.getPositionX() + posConf.groupWidth[row] * g + posConf.paiADistance[row] * g);
                    if (row == 1 || row == 3) groupNode.setPositionY(group0.getPositionY() + posConf.groupHeight[row] * g + posConf.paiADistance[row] * g);
                    groupNode.setName('g' + g);
                    groupNode.setVisible(false);
                    group0.getParent().addChild(groupNode);
                }
                var node = $('row' + row + '.g' + g + '.b' + id);
                cache[row][g][id] = node;
                return node;
            };
        },
        getGPaiId: function (row, g, id) {
            var userData = $('row' + row + '.g' + g + '.b' + id).getUserData();
            return userData.pai;
        },
        checkPaiAmount: function () {
            if (cc.sys.isNative)
                return;
            var amount = 0;
            var row = 2;
            for (var j = 0; j < 4; j++) {
                var g = $('row' + row + '.g' + j);
                if (!g || !$('row' + row + '.g' + j).isVisible())
                    break;
                else
                    amount += 3;
            }
            for (var j = 0; j < 14; j++)
                if (this.getPai(row, j).isVisible())
                    amount += 1;
            if (amount < 13 || amount > 14)
                alert('你的牌数量可能不对: ' + amount + ', 数一下');
        },
        recalcPos: function (row) {
            var g0 = $('row' + row + '.g' + 0);
            var g0b0pos = getPositionRelativeToParent(this.getGPai(row, 0, 0), 2);
            for (var i = 1; i < 4; i++) {
                var g = $('row' + row + '.g' + i);
                if (g && g.isVisible()) {
                    if (row == 0 || row == 2)
                        g.setPositionX(g0.getPositionX() + (posConf.groupWidth[row] * i + posConf.groupDistance[row] * i) * (row == 2
                                                                                                                             ? 1
                                                                                                                             : -1));
                    if (row == 1 || row == 3)
                        g.setPositionY(g0.getPositionY() + (posConf.groupHeight[row] * i + posConf.groupDistance[row] * i) * (row == 1
                                                                                                                              ? 1
                                                                                                                              : -1));
                }
                else
                    break;
            }
            var k = i;
            var m = (k > 1 || g0.isVisible()
                     ? 1
                     : 0);

            var a0 = this.getPai(row, 0);
            var to = 0;
            var p = (row == 1 || row == 2
                     ? 1
                     : -1);
            if (row == 0 || row == 2) to = !m
                                           ? posConf.paiA0PosBak[row].x
                                           : g0b0pos.x + (posConf.groupWidth[row] * k + posConf.groupDistance[row] * k + posConf.groupToFirstPaiDistance[row]) * p;
            if (row == 1 || row == 3) to = !m
                                           ? posConf.paiA0PosBak[row].y
                                           : g0b0pos.y + (posConf.groupHeight[row] * k + posConf.groupDistance[row] * k + posConf.groupToFirstPaiDistance[row]) * p;
            if (row == 0 || row == 2) a0.setPositionX(to);
            if (row == 1 || row == 3) a0.setPositionY(to);
            for (var i = 1; i < 13; i++) {
                var a = this.getPai(row, i);
                var userData = a.getUserData();
                if (row == 0) a.setPosition(a0.getPositionX() + i * posConf.paiADistance[row] + (a.getUserData().pai > 0) * i * posConf.paiALiangDistance[row], a0.getPositionY());
                if (row == 2) {
                    a.setPositionX(a0.getPositionX() + i * posConf.paiADistance[row] + (a.getUserData().pai > 0) * i * posConf.paiALiangDistance[row]);
                    if (!userData.isUpping && !userData.isDowning)
                        a.setPositionY(userData.isUp
                                       ? posConf.upPaiPositionY
                                       : posConf.downPaiPositionY);
                }
                if (row == 1 || row == 3) a.setPosition(a0.getPositionX(), a0.getPositionY() + i * posConf.paiADistance[row] + (a.getUserData().pai > 0) * i * posConf.paiALiangDistance[row]);
            }

            // recalc pai 13 position
            for (var i = 12; i >= 0; i--) {
                var pai = this.getPai(row, i);
                if (pai && pai.isVisible()) {
                    var userData = pai.getUserData();
                    var p = (row == 1 || row == 2
                             ? 1
                             : -1);
                    if (row == 0) this.getPai(row, 13).setPosition(pai.getPositionX() + posConf.paiADistance[row] + posConf.paiMopaiDistance[row] * p, a0.getPositionY());
                    if (row == 2) {
                        this.getPai(row, 13).setPositionX(pai.getPositionX() + posConf.paiADistance[row] + posConf.paiMopaiDistance[row] * p);
                        if (!userData.isUpping && !userData.isDowning)
                            a.setPositionY(userData.isUp
                                           ? posConf.upPaiPositionY
                                           : posConf.downPaiPositionY);
                    }
                    if (row == 1 || row == 3) this.getPai(row, 13).setPosition(a0.getPositionX(), pai.getPositionY() + posConf.paiADistance[row] + posConf.paiMopaiDistance[row] * p);
                    break;
                }
            }

            posConf.paiPos[row] = [];
            for (var i = 0; i < 14; i++) {
                posConf.paiPos[row].push(this.getPai(row, i).getPosition());
            }
            for (var i = 14; i < 18; i++) {
                var pai = $('row' + row + '.a' + i);
                if (pai)
                    pai.setVisible(false);
            }
        },
        hidePai: function (row, id) {
            this.getPai(row, id).setVisible(false);
        },
        getPaiArr: function () {
            return this.getPaiArrOfRow(2);
        },
        getPaiArrOfRow: function (row) {
            var arr = [];
            for (var j = 0; j < 14; j++) {
                var pai = this.getPai(row, j);
                var userData = pai.getUserData();
                if (userData.pai > 0)
                    arr.push(userData.pai);
            }
            return arr;
        },
        getPaiCoutOfRow: function (row) {
            var count = 0;
            for (var i = 0; i < 14; i++) {
                var pai = this.getPai(row, j);
                if (pai.isVisible()) {
                    count += 1;
                }
            }
            return count;
        },
        addUsedPai: function () {
            var cache = {};
            var that = this;
            return function (row, val) {
                cache[row] = cache[row] || {};
                for (var idx = 0; idx < 60; idx++) {
                    // var j = idx + parseInt(idx / 8) * 2;
                    var j = idx;
                    var pai = cache[row][j] || $('row' + row + '.c0.b' + j);
                    if (!pai) {
                        var k = parseInt(j / 10) * 10;
                        var b = $('row' + row + '.c0.b' + k);
                        if (!b) {
                            var b0 = $('row' + row + '.c0.b0');
                            var b10 = $('row' + row + '.c0.b10');
                            b = duplicateNode(b0,true);
                            b.setName('b' + k);
                            if (row == 0) b.setPositionY(parseInt(j / 10) * (b10.getPositionY() - b0.getPositionY()) + b0.getPositionY());
                            if (row == 1) b.setPositionX(parseInt(j / 10) * (b10.getPositionX() - b0.getPositionX()) + b0.getPositionX());
                            if (row == 2) b.setPositionY(parseInt(j / 10) * (b10.getPositionY() - b0.getPositionY()) + b0.getPositionY());
                            if (row == 3) b.setPositionX(parseInt(j / 10) * (b10.getPositionX() - b0.getPositionX()) + b0.getPositionX());
                            b0.getParent().addChild(b);
                            if (row == 2)
                                b.setLocalZOrder(k * -1);
                            pai = b;
                            pai.setVisible(false);
                        }
                        if (!pai) {
                            pai = duplicateNode(b,true);
                            if (row == 0 || row == 2) pai.setPositionX(posConf.paiUsedDistance[row] * (j - k) + b.getPositionX());
                            if (row == 1 || row == 3) pai.setPositionY(posConf.paiUsedDistance[row] * (j - k) + b.getPositionY());
                            pai.setName('b' + j);
                            pai.setVisible(false);
                            b.getParent().addChild(pai, j * posConf.paiUsedZOrder[row][k]);
                            cache[row][j] = pai;
                        }
                    }

                    pai.setUserData({idx: j, pai: val});

                    if (!pai.isVisible()) {
                        //var userData = pai.getUserData();
                        var paiName = getPaiNameByRowAndId(row, val, true);
                        //userData.pai = val;
                        setSpriteFrameByName(pai, paiName, that.getPaiPlist());
                        pai.setVisible(true);
                        if (val == laiziPaiId) {
                            grayYellow(pai);
                        }
                        else {
                            Filter.remove(pai);
                            recoverColor(pai);//恢复颜色
                        }

                        return pai;
                    }
                }
            };
        },
        removeOneTopUsedPai: function (row, paiId) {
            for (var j = 23; j >= 0; j--) {
                var pai = $('row' + row + '.c0.b' + j);
                if (pai && pai.isVisible()) {
                    var userData = pai.getUserData();
                    if (!_.isUndefined(paiId) && userData.pai != paiId)
                        return;
                    userData.pai = 0;
                    pai.setVisible(false);
                    break;
                }
            }
            this.hideArrow();
        },

        /**
         * 游戏中隐藏所有的准备
         * @private
         * */
        _hideReady: function () {
            for (var i = 0; i < 4; i++) {
                safeHide($('info' + i + '.ok'));
                safeHide($('info' + i + '.ti'));
                safeHide($('info' + i + '.btn_invite'));
            }
            safeHide($('btn_zhunbei'));
            safeHide($('img_dengdaijiaru'));
        },

        getRoomState: function () {
            return roomState;
        },

        /**
         * 刷新局数和剩余牌数
         * @param {Boolean} [is_show=true]
         * @private
         * */
        _refreshRoundAndPai: function (is_show) {
            if (cc.isUndefined(is_show)) {
                is_show = true;
            }
            //$('timer2.left_pai').setString('剩余\n' + gameData.left_pai_num);
            $('timer2x.leftArea.txt_num').setString(gameData.left_pai_num);
            //safeString($('timer2.left_round'), '局数\n' + gameData.cur_round + '/' + gameData.total_round);
            if (gameData.curRound) {
                safeString($('timer2x.rightArea.txt_jushuNum'), gameData.curRound + '/' + gameData.totalRound + '局');
            }
            safeVisible($('timer'), is_show);
            //safeVisible($('timer2'), is_show);
            safeVisible($('timer2x'), is_show);
        },
        handleWanfaDesp: function (wanfaDesp){
            var removedStrArr =['王钓麻将', '落地扫', '永州扯胡子', '2人PK', '3人激情', '2人玩', '3人玩', '4人玩',
                '局数: 6局', '局数: 8局', '局数: 10局', '群主支付', '房主支付', 'AA支付'];
            var retVal = wanfaDesp;
            var retValArr = retVal.split(',');
            var locationArr = [];
            for (var i = 0; i < retValArr.length; i++){
                retValArr[i] = retValArr[i].trim();
                if (removedStrArr.indexOf(retValArr[i]) > -1) locationArr.push(i);
            }

            for (var i = locationArr.length - 1; i > -1; i--){
                retValArr.splice(locationArr[i], 1);
            }

            retVal = retValArr.join(',');

            return retVal;
        },
        /**
         * 刷新房间状态
         * @param {Number} state
         * @param isReconnect 重连标记
         * @private
         * */
        _refreshRoomState: function (state, isReconnect) {
            this._room_state = state;
            var arr = decodeURIComponent(gameData.wanfaDesp != 'null'
                                         ? gameData.wanfaDesp
                                         : '').split(',');
            if (arr.length >= 1)
                arr = arr.slice(0);
            var wanfaStr = arr.join(',');
            if (this._room_state === majiang.RoomState.CREATED) {
                try {
                    if (gameData.club_id && !isReplay) {
                        this.assistantLayer = this.getChildByName('assistantLayer');
                        if (!this.assistantLayer) {
                            this.assistantLayer = new ClubAssistantLayer(playerNum);
                            this.assistantLayer.setName('assistantLayer');
                            this.addChild(this.assistantLayer);
                        }
                    }
                } catch (e) {
                    console.log('error in this.assistantLayer e :' + e.toString());
                }
                this.hideControlBtns(false);
                $('signal').setVisible(false);
                // $('setting').setVisible(false);
                // $('chat').setVisible(false);
                $('timer').setVisible(false);
                //$('timer2').setVisible(false);
                $('timer2x').setVisible(false);
                // tn_c$('btn_invite').setVisible(gameData.loginType != 'yk' && gameData.uid == gameData.ownerUid);
                // $('bopyinfo').setVisible(gameData.loginType&&gameData.loginType != 'yk' && gameData.uid == gameData.ownerUid);
                $('btn_copyinfo').setVisible(false);//(!window.inReview);
                $('btn_invite').setVisible(!window.inReview);
                $('img_dengdaijiaru').setVisible(false);
                if (isReplay) {
                    $('btn_invite').setVisible(false);
                }
                $('btn_jiesan').setVisible(gameData.uid == gameData.ownerUid);
                if (gameData.uid == gameData.ownerUid){
                    $('btn_jiesan').setVisible(true);
                    $('btn_tuichux').setVisible(false);
                }
                else {
                    $('btn_jiesan').setVisible(false);
                    $('btn_tuichux').setVisible(true);
                }
                $('btn_control_btns').setVisible(false);
                $('btn_chakanjiesuan').setVisible(false);
                $('btn_jixuyouxi').setVisible(false);
                //$('btn_zhunbei.Text_5').setString('准 备');
                $('btn_mic').setVisible(!window.inReview);
                //$('lb_roomid').setString(gameData.roomId);
                $('timer2x.rightArea.txt_fanghaoNum').setString(gameData.roomId);
                safeString($('timer2x.rightArea.txt_jushuNum'), 0 + '/' + gameData.options.jushu + '局');
                $('lb_wanfa').setString(this.handleWanfaDesp(wanfaStr));
                //$('lb_roomid').setVisible(true);

                $('lb_lxhfmNode').setVisible(false);
                // $('lb_lxhfmNode.lb_lxhfm').setString(gameData.roomHFID);

                $('gengduo_bg').setSwallowTouches(true);

                $('row0').setVisible(false);
                $('row1').setVisible(false);
                $('row2').setVisible(false);
                $('row3').setVisible(false);
                //$('btn_info').setVisible(false);
                //this.showLogo();
                if ($('btn_queding')) $('btn_queding').setVisible(false);
                if ($('btn_quxiao')) $('btn_quxiao').setVisible(false);
                if ($('btn_xuanzewancheng')) $('btn_xuanzewancheng').setVisible(false);
                for (var i = 0; i < 4; i++) {
                    $('info' + i).setPosition($('info_n' + i).getPosition());
                    $('info' + i + '.lb_nickname').setVisible(true);
                    $('info' + i + '.lb_score').setVisible(false);
                }
                this.hideArrow();
                disabledChuPaiIdMap = {};

                lianging = false;
                afterLianging = false;
            }
            if (this._room_state === majiang.RoomState.ONGOING) {
                if (this.assistantLayer && cc.sys.isObjectValid(this.assistantLayer)) {
                    this.assistantLayer.removeFromParent(true);
                    this.assistantLayer = null;
                }
                $('signal').setVisible(!isReplay);
                $('btn_chakanjiesuan').setVisible(false);
                $('btn_invite').setVisible(false);
                $('btn_copyinfo').setVisible(false);
                $('btn_jiesan').setVisible(false);
                $('btn_tuichux').setVisible(false);
                $('btn_zhunbei').setVisible(false);
                $('btn_jixuyouxi').setVisible(false);
                $('img_dengdaijiaru').setVisible(false);

                $('btn_control_btns').setVisible(false);
                this.showControlBtns();
                $('btn_yxks').setVisible(false);
                $('btn_mic').setVisible(!window.inReview);
                //$('lb_roomid').setString(gameData.roomId);
                $('timer2x.rightArea.txt_fanghaoNum').setString(gameData.roomId);
                $('lb_wanfa').setString(this.handleWanfaDesp(wanfaStr));
                $('row0.c0').setVisible(true);
                if ($('btn_queding')) $('btn_queding').setVisible(false);
                if ($('btn_quxiao')) $('btn_quxiao').setVisible(false);
                if ($('btn_xuanzewancheng')) $('btn_xuanzewancheng').setVisible(false);
                //$('lb_roomid').setVisible(false);
                $('row0').setVisible(true);
                $('row1').setVisible(true);
                $('row2').setVisible(true);
                $('row3').setVisible(true);
                safeHide($('btn_zhunbei'));
                safeHide($('btn_jixuyouxi'));

                $('row0.mid').removeAllChildren();
                $('row1.mid').removeAllChildren();
                $('row2.mid').removeAllChildren();
                $('row3.mid').removeAllChildren();

                for (var i = 0; i < 4; i++) {
                    if (roomState == ROOM_STATE_CREATED)
                        $('info' + i).runAction(cc.moveTo(0.5, posConf.headPosBak[i]));
                    else
                        $('info' + i).setPosition(posConf.headPosBak[i]);

                    $('info' + i + '.ok').setVisible(false);
                    $('info' + i + '.ti').setVisible(false);
                    $('info' + i + '.lb_nickname').setVisible(true);
                    $('info' + i + '.lb_score').setVisible(true);
                }

                if (isReplay) {
                    $('chat').setVisible(false);
                }
            }
            if (this._room_state === majiang.RoomState.ENDED) {
                if (this.assistantLayer && cc.sys.isObjectValid(this.assistantLayer)) {
                    this.assistantLayer.removeFromParent(true);
                    this.assistantLayer = null;
                }
                if ($('btn_queding')) $('btn_queding').setVisible(false);
                if ($('btn_quxiao')) $('btn_xuanzewancheng').setVisible(false);
                if ($('btn_xuanzewancheng')) $('btn_xuanzewancheng').setVisible(false);

                $('btn_invite').setVisible(false);
                $('btn_tuichux').setVisible(false);
                $('btn_jiesan').setVisible(false);
                if (isReconnect && isReconnect == true){
                    $('btn_zhunbei').setVisible(true);
                    $('btn_chakanjiesuan').setVisible(false);
                }
                $('img_dengdaijiaru').setVisible(false);
                this.hideChiPengGangHu();
                this.hideArrow();
                disabledChuPaiIdMap = {};

                lianging = false;
                afterLianging = false;

                hideGangStep = 0;
                hideGangArr = [];
                hidedGangArr = [];
                hideGangChupaiArr = [];
            }
            roomState = this._room_state;
        },
        setDuiArr: function (row, duiArr) {
            for (var j = 0; j < 4; j++) {
                var g = $('row' + row + '.g' + j);
                if (g && g.isVisible())
                    g.setVisible(false);
            }
            for (var j = 0; j < duiArr.length; j++) {
                var dui = duiArr[j];
                if (dui.type == 1) this.setGChi(row, j, dui['pai_arr']);
                if (dui.type == 2) this.setGPeng(row, j, dui['pai_arr'][0]);
                if (dui.type == 3) this.setGGang(row, j, dui['pai_arr'][0], dui['pai_arr'][0]);
                if (dui.type == 4) this.setGGang(row, j, dui['pai_arr'][0], 0);
                if (dui.type == 5) this.setGHide(row, j);
            }
        },
        clearTable4StartGame: function (isInitPai, isReconnect, reconnectData) {
            var that = this;
            this.onPlayerEnterExit();
            if (isInitPai) {
                forRows(function (i) {
                    var a0 = $('row' + i + '.a0');
                    if (a0.getPosition().x != posConf.paiA0PosBak[i].x || a0.getPosition().y != posConf.paiA0PosBak[i].y) {
                        a0.setPosition(posConf.paiA0PosBak[i]);
                        for (var j = 1; j < 13; j++) {
                            var node = $('row' + i + '.a' + j);
                            if (i == 0 || i == 2) node.setPositionX(posConf.paiADistance[i] * j + a0.getPositionX());
                            if (i == 1 || i == 3) node.setPositionY(posConf.paiADistance[i] * j + a0.getPositionY());
                        }
                    }
                });
                for (var i = 0; i < 4; i++) {
                    for (var j = 0; j < 4; j++) {
                        this.getPai(i, j).setVisible(false);
                    }
                    for (var k = 0; k < 4; k++) {
                        var g = $('row' + i + '.g' + k);
                        if (g)
                            g.setVisible(false);
                    }
                    for (var k = 0; k < 4; k++) {
                        this.getGPai(i, 0, k).setUserData({idx: k});
                    }
                    $('row' + i + '.c0.b0').setVisible(false);
                    $('row' + i + '.c0.b1').setVisible(false);
                    $('row' + i + '.c0.b10').setVisible(false);
                }
                forRows(function (i) {
                    for (var j = 0; j < 14; j++) {
                        this.getPai(i, j).setOpacity(0);
                    }
                    var c0 = $('row' + i + '.c0');
                    if (i == 0)
                        c0.setLocalZOrder(50);
                    for (var j = 0; j < 100; j++) {
                        var t = $('b' + j, c0);
                        if (t) {
                            t.setUserData({idx: j});
                            t.setVisible(false);
                        }
                    }
                });
                that.setHuTipVisible(false);
            }

            $('cpghg').setVisible(false);
            //#region 添加按钮特效
            that.showBtnActAnimation($('cpghg.chi.aniNode'), 'chi', true);
            that.showBtnActAnimation($('cpghg.peng.aniNode'), 'peng', true);
            that.showBtnActAnimation($('cpghg.gang.aniNode'), 'gang', true);
            that.showBtnActAnimation($('cpghg.hu.aniNode'), 'hu', true);
            that.showBtnActAnimation($('cpghg.guo.aniNode'), 'guo', true);
            //#endregion


            $('timer').setVisible(true);
            $('timer2x').setVisible(true);

            //this.recalcPos(2);

            if (isReconnect) {
                hasChupai = reconnectData['has_chu'];
                that.setZhuang(uid2position[gameData.zhuangUid]);
                gameData.left_pai_num = reconnectData['left_pai_num'];
                this._refreshRoundAndPai();
                this._laiziPaiArr = reconnectData['laiziPaiArr'] || [32]; // 癞子牌数组
                var playerPaiArr = reconnectData['player_pai'];
                for (var i = 0; i < playerPaiArr.length; i++) {
                    var playerPai = playerPaiArr[i];
                    var isOffline = !!playerPai['is_offline'];
                    if (isOffline) {
                        this.playerOnloneStatusChange(uid2position[playerPai.uid], isOffline);
                    }
                    this._onPiao({
                        uid: playerPai.uid,
                        piao: playerPai.piao
                    });
                    var row = uid2position[playerPai.uid];
                    if (row != 2
                        && roomState == ROOM_STATE_ONGOING
                        && playerPai['pai_arr'].length == 0) {
                        for (var j = 0; j < playerPai['cur_pai_num']; j++)
                            playerPai['pai_arr'].push(0);
                    }
                    if (row == 2 && playerPaiArr[i]['is_ting']) {
                        afterLianging = true;
                    }
                    if ($('info' + row + '.liang'))
                        $('info' + row + '.liang').setVisible(playerPaiArr[i]['is_ting']);
                    that.setPaiArrOfRow(row, playerPai['pai_arr'], (row != 2), (row != 2), playerPai['liang_pai_arr']);
                    var liangPaiArr = playerPai['liang_pai_arr'] || [];
                    for (var j = 0; j < liangPaiArr.length; j++)
                        disabledChuPaiIdMap[liangPaiArr[j]] = true;
                    //playerPai['pai_arr'].sort(compareTwoNumbers);
                    //var paiArr = playerPai['pai_arr'];
                    //for (var j = 0; j < paiArr.length; j++)
                    //    this.setPai(row, j, paiArr[j], (row != 2), (row != 2), true).setOpacity(255);
                    //for (; j < 14; j++)
                    //    this.setPai(row, j, 0, (row != 2), (row != 2)).setVisible(false);
                    var usedPaiArr = playerPaiArr[i]['used_pai_arr'];
                    for (var j = 0; j < usedPaiArr.length; j++)
                        this.addUsedPai(row, usedPaiArr[j]);
                    var duiArr = playerPaiArr[i]['dui_arr'];
                    this.setDuiArr(row, duiArr);

                    if (mapId == MAP_ID_WUHAN_KAIKOU || mapId == MAP_ID_WUHAN_KOUKOU)
                        $('info' + row + '.lb_bs').setString('x' + playerPai['multiple']);
                }

                forRows(function (i) {
                    this.recalcPos(i);
                });

                if (roomState == ROOM_STATE_ONGOING) {
                    this.throwTurn(uid2position[reconnectData['turn_uid']]);
                    this.enableChuPai();
                }
                else if (roomState == ROOM_STATE_ENDED) {
                    for (var i = 0; i < playerPaiArr.length; i++) {
                        var playerPai = playerPaiArr[i];
                        var isReady = !!playerPai['is_ready'];
                        if (isReady)
                            that.setReady(playerPai['uid']);
                    }
                }
            }
            else if (isInitPai) {
                forRows(function (i) {
                    this.recalcPos(i);
                });
            }
            gameData.huTipData = null;
            // for (var i = 0; i < 4; i++)
            //     if (i != 0)
            //         for (var j = 1; j <= 25; j++)
            //             this.addUsedPai(i, j);
        },

        /**
         * 检测红中是否可出
         * @param {Number} pai_id
         * @private
         * */
        _checkChuPai: function (pai_id) {
            if (pai_id !== 32) {
                return true;
            }
            var arr = this.getPaiArr();
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] !== 32) {
                    return false;
                }
            }
            return true;
        },

        sendChuPai: function (row, idx, paiId) {
            network.stop([3008, 4002, 4020, 4990, 3007]);
            if (this._checkChuPai(paiId)) {
                network.send(4002, {room_id: gameData.roomId, pai_id: paiId, idx: idx});
                hasChupai = true;
            } else {
                this.downPai(2, idx);
                this.recalcPos(2);
                hasChupai = false;
                network.start();
                showAlert('手里有其它牌时,不能出王牌');
            }
        },
        // chuPai: function (row, idx, paiId, paiArr, liangPaiArr) {
        //     var that = this;
        //     if (paiId == laiziPaiId && (mapId == MAP_ID_LEIYANG || mapId == MAP_ID_LEIYANGHONGZHONG)) {
        //         that.playShaGuiAnim(row);
        //     }
        //     if (liangStep == 2) {
        //         liangStep = 0;
        //         // network.start();
        //         that.downPai(row, idx);
        //         return;
        //     }
        //
        //     if (row != 2 && !isReplay)
        //         idx = 13;
        //
        //     //this.playEffect('vCardOut');
        //
        //     var duration = 0.25;
        //     var delayDuration = 0.65;
        //
        //     var pai = this.getPai(row, idx);
        //     var midNode = $('row' + row + '.mid');
        //     var moveToMidPos = midNode.getPosition();
        //     var usedPai = this.addUsedPai(row, paiId);
        //     if (!cc.sys.isObjectValid(usedPai)) {
        //         return;
        //     }
        //     usedPai.setOpacity(0);
        //     that.playerOnloneStatusChange(row, false);
        //
        //     var positionBak = pai.getPosition();
        //     var scaleBak = pai.getScaleX();
        //
        //     moveToMidPos.y += UPPAI_Y;
        //     pai.setVisible(false);
        //
        //     var _paiBg = new cc.Sprite(majiang.res.mjbg_png);
        //     _paiBg.setScale(CHUPAI_MID_NODE_SCALE_MAP[row] / midNode.getParent().getScaleX());
        //     _paiBg.setName('paiBg');
        //     _paiBg.setOpacity(188);
        //     midNode.addChild(_paiBg);
        //
        //     var _pai = new cc.Sprite();
        //     _pai.setName('pai');
        //     midNode.addChild(_pai);
        //
        //     var paiName = getPaiNameByRowAndId(2, paiId, false, false);
        //     setSpriteFrameByName(_pai, paiName, 'submodules/majiang/pai');
        //     _pai.setScale(CHUPAI_MID_NODE_SCALE_MAP[row] / midNode.getParent().getScaleX());
        //     _pai.setVisible(true);
        //     _paiBg.setVisible(true);
        //     var fangda = cc.sys.localStorage.getItem('fangda') == 1;
        //     if (fangda) {
        //         _pai.runAction(cc.sequence(cc.delayTime(delayDuration), cc.callFunc(function () {
        //             _pai.removeFromParent(true);
        //             _paiBg.removeFromParent(true);
        //         })));
        //     } else {
        //         _pai.removeFromParent(true);
        //         _paiBg.removeFromParent(true);
        //     }
        //     //动画
        //     var func = function () {
        //         that.setPaiArrOfRow(row, paiArr, (row != 2), (row != 2), []);
        //
        //         if (row == 2) {
        //             pai.setPosition(posConf.paiPos[2][idx]);
        //             pai.setScale(posConf.paiA0ScaleBak[row][0], posConf.paiA0ScaleBak[row][1]);
        //             that.upPai(row, -1);
        //             that.recalcPos(row);
        //             that.showArrow(usedPai, row);
        //
        //             that.checkPaiAmount();
        //         }
        //         else {
        //             pai.setPosition(positionBak);
        //             pai.setScale(scaleBak);
        //
        //             that.setPaiArrOfRow(row, paiArr, (row != 2), (row != 2), liangPaiArr);
        //             that.recalcPos(row);
        //             that.showArrow(usedPai, row);
        //         }
        //
        //         usedPai.runAction(cc.fadeIn(duration));
        //
        //         // if (!noSound)
        //         playEffect('vp' + paiId, position2sex[row]);
        //         network.start();
        //     };
        //     if (row == 2 || isReplay) {
        //         var animPaiArr = [];
        //         var oldPaiArr = that.getPaiArrOfRow(row);
        //         if (idx == oldPaiArr.length - 1) {
        //             func();
        //             return;
        //         }
        //         var lastPai = that.getPai(row, 13);
        //         if (!lastPai.isVisible()) {
        //             func();
        //             return;
        //         }
        //         var newIdx = that.sortPaiArr(paiArr, row).lastIndexOf(lastPai.getUserData().pai);
        //         var parent = that.getPai(row, 0).getParent();
        //         if (idx != newIdx) {
        //             for (var i = Math.min(idx + 1, newIdx); i < Math.max(idx, newIdx + 1); i++) {
        //                 var temp_pai = duplicateNode(that.getPai(row, i));
        //                 parent.addChild(temp_pai);
        //                 animPaiArr.push(temp_pai);
        //             }
        //         }
        //         var animPai = duplicateNode(lastPai);
        //         parent.addChild(animPai);
        //
        //         func();
        //
        //         for (var i = Math.min(idx, newIdx); i <= Math.max(idx, newIdx); i++) {
        //             that.getPai(row, i).setVisible(false);
        //         }
        //         // that.getPai(row, paiArr.length - 1).setVisible(false);
        //
        //         if (newIdx == paiArr.length - 1) {
        //             var ptConf = [
        //                 {x: that.getPai(row, paiArr.length - 1).getPositionX(), y: posConf.paiA0PosBak[row].y},
        //                 {x: posConf.paiA0PosBak[row].x, y: that.getPai(row, paiArr.length - 1).getPositionY()},
        //                 {x: that.getPai(row, paiArr.length - 1).getPositionX(), y: posConf.paiA0PosBak[row].y},
        //                 {x: posConf.paiA0PosBak[row].x, y: that.getPai(row, paiArr.length - 1).getPositionY()}
        //             ];
        //             animPai.runAction(cc.sequence(
        //                 cc.moveTo(0.2, ptConf[row].x, ptConf[row].y),
        //                 cc.callFunc(function () {
        //                     animPai.removeFromParent();
        //                     that.getPai(row, newIdx).setVisible(true);
        //                 })
        //             ));
        //         } else {
        //             var ptConf = [
        //                 [
        //                     {x: 0, y: -animPai.getContentSize().height - 5},
        //                     {
        //                         x: that.getPai(row, newIdx).getPositionX(),
        //                         y: posConf.paiA0PosBak[row].y - animPai.getContentSize().height - 5
        //                     },
        //                     {x: 0, y: animPai.getContentSize().height + 5}
        //                 ],
        //                 [
        //                     {x: -animPai.getContentSize().width - 5, y: 0},
        //                     {
        //                         x: posConf.paiA0PosBak[row].x - animPai.getContentSize().width - 5,
        //                         y: that.getPai(row, newIdx).getPositionY()
        //                     },
        //                     {x: animPai.getContentSize().width + 5, y: 0}
        //                 ],
        //                 [
        //                     {x: 0, y: animPai.getContentSize().height + 5},
        //                     {
        //                         x: that.getPai(row, newIdx).getPositionX(),
        //                         y: posConf.paiA0PosBak[row].y + animPai.getContentSize().height + 5
        //                     },
        //                     {x: 0, y: -animPai.getContentSize().height - 5}
        //                 ],
        //                 [
        //                     {x: animPai.getContentSize().width + 5, y: 0},
        //                     {
        //                         x: posConf.paiA0PosBak[row].x + animPai.getContentSize().width + 5,
        //                         y: that.getPai(row, newIdx).getPositionY()
        //                     },
        //                     {x: -animPai.getContentSize().width - 5, y: 0}
        //                 ]
        //             ];
        //             animPai.runAction(cc.sequence(
        //                 cc.moveBy(0.1, ptConf[row][0].x, ptConf[row][0].y),
        //                 cc.moveTo(0.2, ptConf[row][1].x, ptConf[row][1].y),
        //                 cc.moveBy(0.1, ptConf[row][2].x, ptConf[row][2].y),
        //                 cc.callFunc(function () {
        //                     animPai.removeFromParent();
        //                     that.getPai(row, newIdx).setVisible(true);
        //                 })
        //             ));
        //         }
        //         var moveX = (row == 0 || row == 2)
        //                     ? posConf.paiADistance[row]
        //                     : 0;
        //         var moveY = (row == 0 || row == 2)
        //                     ? 0
        //                     : posConf.paiADistance[row];
        //         for (var i = 0; i < animPaiArr.length; i++) {
        //             (function (k, animpai) {
        //                 animpai.runAction(cc.sequence(
        //                     cc.moveBy(0.2, idx < newIdx
        //                                    ? -moveX
        //                                    : moveX, idx < newIdx
        //                                             ? -moveY
        //                                             : moveY),
        //                     cc.callFunc(function () {
        //                         animpai.removeFromParent();
        //                         that.getPai(row, Math.min(idx, newIdx + 1) + k).setVisible(true);
        //                     })
        //                 ));
        //             })(i, animPaiArr[i]);
        //         }
        //     } else {
        //         func();
        //     }
        // },
        chuPai: function (row, idx, paiId, paiArr, liangPaiArr) {
            var that = this;
            if (paiId == laiziPaiId && (mapId == MAP_ID_LEIYANG || mapId == MAP_ID_LEIYANGHONGZHONG)) {
                that.playShaGuiAnim(row);
            }
            if (liangStep == 2) {
                liangStep = 0;
                // network.start();
                that.downPai(row, idx);
                return;
            }

            if (row != 2 && !isReplay)
                idx = 13;

            this.playEffect('vCardOut');

            var duration = 0.25;
            var delayDuration = 0.65;

            var pai = this.getPai(row, idx);
            var midNode = $('row' + row + '.mid');
            var moveToMidPos = midNode.getPosition();
            var usedPai = this.addUsedPai(row, paiId);
            usedPai.setOpacity(0);
            that.playerOnloneStatusChange(row, false);

            var positionBak = pai.getPosition();
            var scaleBak = pai.getScaleX();

            var userData = pai.getUserData();
            moveToMidPos.y += UPPAI_Y;
            pai.setVisible(false);

            var _paiBg = new cc.Sprite(majiang.res.mjbg_png);
            _paiBg.setScale(CHUPAI_MID_NODE_SCALE_MAP[row] / midNode.getParent().getScaleX());
            _paiBg.setName('paiBg');
            _paiBg.setOpacity(188);
            midNode.addChild(_paiBg);

            var _pai = new cc.Sprite();
            _pai.setName('pai');
            midNode.addChild(_pai);

            var paiName = getPaiNameByRowAndId(2, paiId, false, false);
            setSpriteFrameByName(_pai, paiName, that.getPaiPlist());
            _pai.setScale(CHUPAI_MID_NODE_SCALE_MAP[row] / midNode.getParent().getScaleX());
            _pai.setVisible(true);
            _paiBg.setVisible(true);
            var fangda = cc.sys.localStorage.getItem('fangda') == 1;
            if (fangda) {
                _pai.runAction(cc.sequence(cc.delayTime(delayDuration), cc.callFunc(function () {
                    _pai.removeFromParent(true);
                    _paiBg.removeFromParent(true);
                })));
            } else {
                _pai.removeFromParent(true);
                _paiBg.removeFromParent(true);
            }
            that.setPaiArrOfRow(row, paiArr, (row != 2), (row != 2), []);

            if (row == 2) {
                pai.setPosition(posConf.paiPos[2][idx]);
                pai.setScale(posConf.paiA0ScaleBak[row][0], posConf.paiA0ScaleBak[row][1]);
                that.upPai(row, -1);
                that.recalcPos(row);
                that.showArrow(usedPai, row);

                that.checkPaiAmount();
            }
            else {
                pai.setPosition(positionBak);
                pai.setScale(scaleBak);

                that.setPaiArrOfRow(row, paiArr, (row != 2), (row != 2), liangPaiArr);
                that.recalcPos(row);
                that.showArrow(usedPai, row);
            }

            usedPai.runAction(cc.fadeIn(duration));
            network.start();
            playEffect('vp' + paiId, position2sex[row]);
        },

        checkPaiPos: function (row) {
            for (var j = 0; j < 14; j++) {
                var pai = this.getPai(row, j);
                var userData = pai.getUserData();
                //pai.setPositionX(posConf.paiPos[2][j].x);
                //console.log(j + '  ' + userData.isUp);
                if (!userData.isUpping && !userData.isDowning)
                    pai.setPosition(posConf.paiPos[2][j].x, (userData.isUp
                                                             ? posConf.upPaiPositionY
                                                             : posConf.downPaiPositionY));
            }
        },
        upPai: function (row, idx) {
            var that = this;
            this.checkPaiPos(row);
            if (liangStep == 2 && idx >= 0) {
                var pai = that.getPai(row, idx);
                var userData = pai.getUserData();
                if (userData.isUp && !userData.isDowning) {
                    userData.isDowning = true;
                    pai.runAction(cc.sequence(
                        cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                                                            ? posConf.upPaiPositionY
                                                            : posConf.downPaiPositionY))
                        , cc.callFunc(function () {
                            userData.isUp = false;
                            userData.isDowning = false;
                        })
                    ));
                }
                else if (!userData.isUpping) {
                    userData.isUpping = true;
                    pai.runAction(cc.sequence(
                        cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                                                            ? posConf.upPaiPositionY
                                                            : posConf.downPaiPositionY))
                        , cc.callFunc(function () {
                            userData.isUp = true;
                            userData.isUpping = false;
                        })
                    ));
                }
                return;
            }
            for (var i = 0; i < 14; i++) {
                (function (j) {
                    var pai = that.getPai(row, j);
                    var userData = pai.getUserData();
                    if (idx == j && userData.isUp) {
                        that.sendChuPai(row, idx, userData.pai);
                        userData.isUp = false;
                    }
                    else if (idx == j && !userData.isUp && !userData.isUpping) {
                        userData.isUpping = true;
                        pai.runAction(cc.sequence(
                            cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                                                                ? posConf.upPaiPositionY
                                                                : posConf.downPaiPositionY))
                            , cc.callFunc(function () {
                                userData.isUp = true;
                                userData.isUpping = false;
                            })
                        ));
                    }
                    else if (idx != j && userData.isUp && !userData.isDowning) {
                        userData.isDowning = true;
                        pai.runAction(cc.sequence(
                            cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                                                                ? posConf.upPaiPositionY
                                                                : posConf.downPaiPositionY))
                            , cc.callFunc(function () {
                                userData.isUp = false;
                                userData.isDowning = false;
                            })
                        ));
                    }
                })(i);
            }
        },
        downPai: function (row, idx) {
            var that = this;
            this.checkPaiPos(row);
            var pai = that.getPai(row, idx);
            var userData = pai.getUserData();
            if (!userData.isUp || userData.isDowning)
                return;
            userData.isDowning = true;
            pai.runAction(cc.sequence(
                cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                                                    ? posConf.upPaiPositionY
                                                    : posConf.downPaiPositionY))
                , cc.callFunc(function () {
                    userData.isUp = false;
                    userData.isDowning = false;
                })
            ));
        },
        enableChuPai: function () {
            if (enableChupaiCnt > 0)
                return;
            enableChupaiCnt++;

            var that = this;

            var curPaiIdx = -1;
            var beganTime, beganPosition;
            var isUp, paiIdx, paiId;
            var positionBak;
            var safeY;
            var toNodeDelta = {};
            var chupaiListener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ONE_BY_ONE,
                swallowTouches: true,
                onTouchBegan: function (touch, event) {
                    if (hasChupai || !that.isMyTurn() || afterLianging || disableChupai || roomState != ROOM_STATE_ONGOING)
                        return false;
                    var pai, _curPaiIdx = -1;
                    for (var i = 0; i < 14; i++) {
                        pai = that.getPai(2, i);
                        var userData = pai.getUserData();
                        if (!pai.isVisible())
                            continue;
                        if (TouchUtil.isTouchMe(pai, touch, event, null)) {
                            _curPaiIdx = i;
                            break;
                        }
                    }

                    if (!pai.getUserData().isLiang)
                        return false;

                    if ((curPaiIdx >= 0 && _curPaiIdx != curPaiIdx) || !(pai.getNumberOfRunningActions() == 0 || !pai.getUserData().isUpping && !pai.getUserData().isDowning))
                        return false;

                    curPaiIdx = _curPaiIdx;

                    if (curPaiIdx >= 0) {
                        var userData = pai.getUserData();

                        for (var k = 0; k < 14; k++)
                            if (that.getPai(2, k).getNumberOfRunningActions() > 0)
                                return false;
                        if (gameData.huTipData) {
                            that.showTishiTip(gameData.huTipData);
                            // console.log("333");
                        }
                        that.playEffect('vCardClick');

                        beganTime = getCurrentTimeMills();

                        // back up
                        userData.positionBak = pai.getPosition();
                        userData.scaleBak = pai.getScaleX();

                        isUp = userData.isUp;
                        if (!isUp || liangStep == 2)
                            that.upPai(2, userData.idx);
                        if (userData.hucards) {
                            var jiaoSp = pai.getChildByName('hucardSprite');
                            if (jiaoSp && jiaoSp.isVisible())
                                that.HuCardTip(userData.hucards, pai.getPositionX(), true);
                        }
                        paiIdx = userData.idx;
                        paiId = userData.pai;
                        positionBak = _.clone(posConf.paiPos[2][curPaiIdx]);
                        positionBak.y = (true || isUp
                                         ? posConf.upPaiPositionY
                                         : posConf.downPaiPositionY);
                        beganPosition = touch.getLocation();
                        safeY = pai.getBoundingBox().height;
                        var a = touch.getLocation();
                        var b = pai.convertToNodeSpace(touch.getLocation());
                        toNodeDelta.x = a.x - b.x;
                        toNodeDelta.y = a.y - b.y;
                    }

                    return curPaiIdx >= 0;
                },
                onTouchMoved: function (touch, event) {
                    if (curPaiIdx < 0)
                        return;

                    var pai = that.getPai(2, curPaiIdx);
                    var userData = pai.getUserData();

                    if (!userData.isLiang)
                        return;

                    if (beganPosition) {
                        var p = touch.getLocation();
                        p.x -= toNodeDelta.x;
                        p.y -= toNodeDelta.y;
                        if (p.y < safeY) {
                            if (pai.getNumberOfRunningActions() <= 0)
                                pai.setPosition(positionBak);
                            return;
                        }
                        p = pai.convertToNodeSpace(touch.getLocation());
                        p.x += pai.getPositionX() - pai.getBoundingBox().width / 2;
                        p.y += pai.getPositionY() - pai.getBoundingBox().height / 2;
                        //that.setPai(2, 15, userData.pai);
                        pai.setPosition(p);
                    }
                },
                onTouchEnded: function (touch, event) {
                    that.HuCardTip(null, null, false);
                    if (curPaiIdx < 0)
                        return;

                    var pai = that.getPai(2, curPaiIdx);
                    var userData = pai.getUserData();

                    if (beganPosition) {
                        var p = touch.getLocation();
                        p.x -= toNodeDelta.x;
                        p.y -= toNodeDelta.y;
                        var now = getCurrentTimeMills();
                        var isSend = (p.y < safeY && isUp && Math.abs(now - beganTime) < 168) || (p.y > safeY);
                        if (isSend) {
                            if ((mapId == MAP_ID_YIYANG || mapId == MAP_ID_LEIYANGHONGZHONG) && hideGangStep == 2) {
                                hideGangStep = 0;
                                if ($('info' + 2 + '.liang'))
                                    $('info' + 2 + '.liang').setVisible(true);
                                afterLianging = true;
                                setTimeout(function () {
                                    that.playChiPengGangHuAnim(2, OP_TING);
                                    // playEffect('vliang', position2sex[2]);
                                }, 1200);
                            }
                            if (liangStep == 0 && hideGangStep == 0) {
                                that.sendChuPai(2, paiIdx, paiId);
                                that.setHuTipVisible(false);
                            }
                        }
                        else {
                            that.checkPaiPos(2);
                            setTimeout(function () {
                                curPaiIdx = -1;
                                beganPosition = null;
                            }, parseInt(UPDOWNPAI_ANIM_DURATION * 100));
                        }
                    }
                    curPaiIdx = -1;
                    beganPosition = null;
                    return false;
                }
            });
            that.HuCardTip(null, null, false);
            return cc.eventManager.addListener(chupaiListener, $('row2'));
        },
        countDown: function () {
            var that = this;
            var timer = null;
            return function (seconds) {
                if (isReplay) {
                    $('timer.sec').setString('');
                    return;
                }
                if (timer) {
                    clearInterval(timer);
                    timer = null;
                }
                $('timer.sec').setString(seconds);

                timer = setInterval(function () {
                    var sec = $('timer.sec');
                    if (!cc.sys.isObjectValid(sec)) {
                        if (timer)
                            clearInterval(timer);
                        return;
                    }
                    if (!sec) {
                        clearInterval(timer);
                        timer = null;
                        return;
                    }
                    if (seconds > 0) {
                        --seconds;
                        sec.setString(seconds < 10
                                      ? '0' + seconds
                                      : seconds);
                    }
                    if (seconds >= 0 && seconds <= 5 && that.getRoomState() == ROOM_STATE_ONGOING) {
                        //playEffect('vCountDown');
                    }
                    if (seconds == 0) {
                        if (turnRow == 2 && !hasChupai)
                            // vibrate();
                        clearInterval(timer);
                    }
                }, 1000);
            };
        },
        closePai: function (paiId) {

        },
        setPaiArrOfRow: function (row, paiArr, isLittle, isStand, liangPaiArr, liangAll, huPaiId) {
            liangPaiArr = liangPaiArr || [];
            paiArr = this.sortPaiArr(paiArr, row, liangPaiArr, huPaiId);
            paiArr = this._sort(paiArr);

            var lastPai = null;
            for (var j = 0; j < paiArr.length; j++) {
                lastPai = this.setPai(row, j, paiArr[j], isLittle, isStand, true);
                lastPai.setOpacity(255);
            }
            for (; j < 14; j++)
                this.setPai(row, j, 0, isLittle, isStand, false);
            liangPaiArr.sort(compareTwoNumbers);

            if (typeof liangPaiArr !== 'undefined') {
                var cond = (row == 2);
                if (mapId == MAP_ID_CHANGSHA)
                    cond = (cond && afterLianging);
                else
                    cond = (cond && hideGangStep > 0);
                if (cond) {
                    if (mapId == MAP_ID_CHANGSHA) {
                        var pai = this.getPai(2, 13);
                        //Filter.grayMask(pai);
                        grayYellow(pai);
                        pai.getUserData().isLiang = false;
                    }
                    for (var i = 0; i < paiArr.length; i++) {
                        var pai = this.getPai(2, i);
                        //Filter.grayMask(pai);
                        grayYellow(pai);
                        pai.getUserData().isLiang = false;
                    }
                    for (var j = 0; j < liangPaiArr.length; j++) {
                        for (var i = 0; i < paiArr.length; i++) {
                            var pai = this.getPai(2, i);
                            var userData = pai.getUserData();
                            if (userData.pai == liangPaiArr[j] && !userData.isLiang) {
                                userData.isLiang = true;
                                Filter.remove(pai);
                                //this.downPai(2, i);
                                if (!liangAll)
                                    break;
                            }
                            //else
                            //    Filter.grayMask(pai);
                        }
                    }
                }
                else {
                    if (row == 1)
                        for (var j = 0; j < liangPaiArr.length; j++)
                            this.setPai(row, j, liangPaiArr[j], isLittle, isStand, true);
                    if (row == 3)
                        for (var j = 0; j < liangPaiArr.length; j++)
                            this.setPai(row, paiArr.length - liangPaiArr.length + j, liangPaiArr[j], isLittle, isStand, true);
                }
            }
            else if (false && disabledChuPaiIdMap) {
                for (var i = 0; i < paiArr.length; i++) {
                    if (disabledChuPaiIdMap[paiArr[i]]) {
                        var pai = this.getPai(2, i);
                        //Filter.grayMask(pai);
                        grayYellow(pai);
                        pai.getUserData().isLiang = false;
                    }
                }
            }
            if (huPaiId && cc.sys.isObjectValid(lastPai)) {
                lastPai.setOpacity(168);
                this.recalcPos(row);
            }
        },

        /**
         * 牌排序
         * @param {Array} pai_arr
         * @param {Array} [exclude_arr]
         * @private
         * */
        _sort: function (pai_arr, exclude_arr) {
            exclude_arr = exclude_arr || [];
            var arr = deepCopy(pai_arr);
            for (var i = 0; i < exclude_arr.length; i++) {
                _.pull(arr, exclude_arr[i]);
            }
            arr.sort(function (a, b) {
                return a - b;
            });

            // 癞子牌往前放
            if (this._laiziPaiArr.length > 0) {
                for (var laizi_idx = 0; laizi_idx < this._laiziPaiArr.length; laizi_idx++) {
                    this.sortFront(arr, this._laiziPaiArr[laizi_idx]);
                }
            }
            cc.log('癞子牌数组:' + this._laiziPaiArr);
            cc.log('手牌数组：' + arr);
            return arr;
        },

        sortFront: function (paiArr, id) {
            var oldSize = paiArr.length;
            _.pull(paiArr, id);
            if (paiArr.length != oldSize) {
                var t = paiArr.length;
                for (var j = 0; j < oldSize - t; j++)
                    paiArr.splice(0, 0, id);
            }
        },
        mopai: function (row, paiId, paiArr, liangPaiArr) {
            if (row == 2) {
                hasChupai = false;
                this.setPaiArrOfRow(2, paiArr, false, false, liangPaiArr);
            }

            var that = this;
            //动画
            var func = function () {

                that.throwTurn(row);

                if (row == 2)
                    that.recalcPos(2);

                that.countDown(12);
            };

            if (row == 2) {
                network.stop([3008, 4020]);
                var pai = this.setPai(row, 13, (row == 2 || isReplay
                                                ? paiId
                                                : 0), (row != 2), (row != 2), false);
                pai.setOpacity(255);
                var animPai = duplicateNode(pai,true);
                animPai.setVisible(true);
                pai.getParent().addChild(animPai);
                animPai.y += 30;
                animPai.runAction(cc.sequence(
                    cc.moveBy(0.1, 0, -40).easing(cc.easeIn(1.5)),
                    cc.moveBy(0.05, 0, 15),
                    cc.moveBy(0.05, 0, -5),
                    cc.callFunc(function () {
                        network.start();
                        animPai.removeFromParent();
                        pai.setVisible(true);
                        pai.setOpacity(255);
                        func();
                    })
                ));
            } else {
                this.setPai(row, 13, (row == 2 || isReplay
                                      ? paiId
                                      : 0), (row != 2), (row != 2), true)
                    .runAction(cc.fadeIn(MOPAI_ANIM_DURATION));
                func();
            }
        },
        showChiPengGangHu: function (row, paiId, chi, peng, gang, hu, ting, data) {
            var that = this;

            if (!isReplay) {
                var _opPaiIdArr = {};

                var children = $('cpghg').getChildren();
                for (var i = 0; i < children.length; i++) {
                    children[i].setVisible(false);
                }

                if (mapId == MAP_ID_CHANGSHA) {
                    if (!gang) {
                        var nextGang = data['next_gang'];
                        if (nextGang) {
                            _opPaiIdArr[OP_GANG] = nextGang;
                            _opPaiIdArr[OP_TING] = nextGang;
                            gang = 1;
                        }
                    }

                    ting = gang;
                }

                var sum = (chi || 0) + (peng || 0) + (gang || 0) + (hu || 0) + (ting || 0) + 1;
                if (mapId == MAP_ID_YUEYANG_ZHUOXIAZI && data['can_bu']) {
                    sum += 1;
                }
                $('cpghg.chi').setVisible(false);
                $('cpghg.peng').setVisible(false);
                $('cpghg.gang').setVisible(false);
                $('cpghg.hu').setVisible(false);
                $('cpghg.ting').setVisible(false);
                var nodeArr = [], opArr = [];
                if (chi) {
                    nodeArr.push($('cpghg.chi'));
                    opArr.push(OP_CHI);
                }
                if (mapId == MAP_ID_YUEYANG_ZHUOXIAZI && data['can_bu']) {
                    nodeArr.push($('cpghg.chi'));
                    opArr.push(OP_CHI);
                }
                if (peng) {
                    nodeArr.push($('cpghg.peng'));
                    opArr.push(OP_PENG);
                }
                if (gang) {
                    nodeArr.push($('cpghg.gang'));
                    opArr.push(OP_GANG);
                }
                if (hu) {
                    nodeArr.push($('cpghg.hu'));
                    opArr.push(OP_HU);
                }
                if (ting) {
                    nodeArr.push($('cpghg.ting'));
                    opArr.push(OP_TING);
                }
                nodeArr.push($('cpghg.guo'));

                for (var i = 0; i < nodeArr.length; i++) {
                    if (i < nodeArr.length - 1) {
                        var node = $('a', nodeArr[i]);
                        if (!node) {
                            var node = duplicateNode($('row2.c0.b0'),true);
                            node.setName('a');
                            node.setPosition($('n', nodeArr[i]).getPosition());
                            node.setVisible(true);
                            nodeArr[i].addChild(node);
                        }
                        var _paiId = _opPaiIdArr[opArr[i]] || paiId;
                        var paiName = getPaiNameByRowAndId(2, _paiId, true);
                        setSpriteFrameByName(node, paiName, that.getPaiPlist());
                        node.setUserData({paiId: _paiId});
                    }

                    if (typeof posConf.cpghgPositionX[sum][i] === 'number')
                        nodeArr[i].setPositionX(posConf.cpghgPositionX[sum][i]);
                    else
                        nodeArr[i].setPosition(posConf.cpghgPositionX[sum][i]);
                    nodeArr[i].setVisible(true);
                }

                if (mapId == MAP_ID_CHANGSHA && ting) {
                    $('cpghg.ting').setTexture(majiang.res.bu_png);
                }

                if (mapId == MAP_ID_YIYANG && ting) {
                    $('cpghg.ting').setTexture(majiang.res.ting_png);
                }

                if (mapId == MAP_ID_YUEYANG_ZHUOXIAZI && data['can_bu']) {
                    $('cpghg.chi').setTexture(majiang.res.bu_png);
                    $('cpghg.chi.a').setVisible(false);
                }

                chi && TouchUtil.setOnclickListener($('cpghg.chi'), function () {
                    if (mapId == MAP_ID_YUEYANG_ZHUOXIAZI && data['can_bu']) {
                        return;
                    }
                    var _paiId = $('cpghg.chi.a').getUserData().paiId || paiId;
                    that.showChiLayer(_paiId, function (paiId, oriPaiId) {
                        that.sendChiPengGang(OP_CHI, 2, paiId, oriPaiId);
                    });
                });

                peng && TouchUtil.setOnclickListener($('cpghg.peng'), function () {
                    var _paiId = $('cpghg.peng.a').getUserData().paiId || paiId;
                    that.sendChiPengGang(OP_PENG, 2, _paiId);
                    that.hideChiPengGangHu();
                });

                ting && TouchUtil.setOnclickListener($('cpghg.ting'), function () {
                    var _paiId = $('cpghg.ting.a').getUserData().paiId || paiId;
                    if (mapId == MAP_ID_CHANGSHA) {
                        that.sendChiPengGang(OP_GANG, 2, _paiId);
                        that.hideChiPengGangHu();
                    }
                    else if (mapId == MAP_ID_WUHAN_KAIKOU || mapId == MAP_ID_WUHAN_KOUKOU) {

                    }
                    else if (mapId == MAP_ID_KWX_XF || mapId == MAP_ID_YIYANG) {
                        that.hideChiPengGangHu();

                        network.send(4014, {
                            room_id: gameData.roomId,
                            uid: gameData.uid
                        });
                    }
                });

                hu && TouchUtil.setOnclickListener($('cpghg.hu'), function () {
                    var _paiId = $('cpghg.hu.a').getUserData().paiId || paiId;
                    do {
                        if (mapId == MAP_ID_CHANGSHA) {
                            if (selectingXiaohu && gameData.left_pai_num == 55) {
                                that.sendChiPengGang(OP_XIAOHU, 2, _paiId);
                                that.hideChiPengGangHu();
                                break;
                            }
                        }

                        that.sendChiPengGang(OP_HU, 2, _paiId);
                        that.hideChiPengGangHu();
                    } while (false);
                });

                gang && TouchUtil.setOnclickListener($('cpghg.gang'), function () {
                    var _paiId = $('cpghg.gang.a').getUserData().paiId || paiId;
                    if (mapId == MAP_ID_CHANGSHA) {
                        var isKaigang = data['kaigang'];
                        if (!isKaigang) {
                            showMessageBox('确定要【开杠】吗?', function () {
                                that.sendChiPengGang(OP_KAIGANG, 2, _paiId);
                                that.hideChiPengGangHu();
                            }, function () {
                            });
                        }
                        else {
                            that.sendChiPengGang(OP_KAIGANG, 2, _paiId);
                            that.hideChiPengGangHu();
                        }
                    }
                    else {
                        that.sendChiPengGang(OP_GANG, 2, _paiId);
                        that.hideChiPengGangHu();
                    }
                });

                TouchUtil.setOnclickListener($('cpghg.guo'), function () {
                    if (hu && that.isMyTurn()) {
                        that.sendChiPengGang(OP_PASS, 2, paiId);
                        that.hideChiPengGangHu();
                    }
                    else {
                        that.sendChiPengGang(OP_PASS, 2, paiId);
                        that.hideChiPengGangHu();
                    }
                });

                $('cpghg').setVisible(true);

                this.countDown(12);
            } else {
                var cpg = $('cpghRep' + row);
                for (var i = 0; i < 6; i++) {
                    if (!cpg.getChildByName('sp1_' + i)) {
                        var sp = new cc.Sprite(majiang.res['sp1_' + i + '_png']);
                        sp.setPosition(cpg.getChildByName('sp_' + i).getPosition());
                        sp.setName('sp1_' + i);
                        cpg.addChild(sp);
                        sp.setVisible(false);
                    }
                }
                $('cpghRep' + row + '.sp1_0').setVisible(!!chi);
                $('cpghRep' + row + '.sp1_1').setVisible(!!peng);
                $('cpghRep' + row + '.sp1_2').setVisible(!!gang);
                $('cpghRep' + row + '.sp1_3').setVisible(!!hu);
                $('cpghRep' + row + '.sp1_4').setVisible(true);
                $('cpghRep' + row + '.sp1_5').setVisible(false);

                $('cpghRep' + row + '.sp_0').setVisible(!chi);
                $('cpghRep' + row + '.sp_1').setVisible(!peng);
                $('cpghRep' + row + '.sp_2').setVisible(!gang);
                $('cpghRep' + row + '.sp_3').setVisible(!hu);
                $('cpghRep' + row + '.sp_4').setVisible(false);
                $('cpghRep' + row + '.sp_5').setVisible(true);

                var pai = $('cpghRep' + row + '.sp_pai');
                var paiName = getPaiNameByRowAndId(2, paiId, true);
                pai.setScale(0.65, 0.65);
                setSpriteFrameByName(pai, paiName,that.getPaiPlist());
                cpg.setVisible(true);
            }
        },
        showTingLiang: function (row, ting, liang) {
            return;
            var that = this;

            if (!isReplay) {
                $('tl.ting').setVisible(!!ting);
                $('tl.liang').setVisible(!!liang);

                ting && TouchUtil.setOnclickListener($('tl.ting'), function () {
                    that.sendChiPengGang(OP_PENG, 2, paiId);
                    that.hideChiPengGangHu();
                });

                liang && TouchUtil.setOnclickListener($('tl.liang'), function () {
                    that.sendChiPengGang(OP_PENG, 2, paiId);
                    that.hideChiPengGangHu();
                });

                $('tl').setVisible(true);
            } else {
                var cpg = $('cpghRep' + row);
                for (var i = 0; i < 6; i++) {
                    if (!cpg.getChildByName('sp1_' + i)) {
                        var sp = new cc.Sprite(majiang.res['sp1_' + i + '_png']);
                        sp.setPosition(cpg.getChildByName('sp_' + i).getPosition());
                        sp.setName('sp1_' + i);
                        cpg.addChild(sp);
                        sp.setVisible(false);
                    }
                }
                $('cpghRep' + row + '.sp1_0').setVisible(!!chi);
                $('cpghRep' + row + '.sp1_1').setVisible(!!peng);
                $('cpghRep' + row + '.sp1_2').setVisible(!!gang);
                $('cpghRep' + row + '.sp1_3').setVisible(!!hu);
                $('cpghRep' + row + '.sp1_4').setVisible(true);
                $('cpghRep' + row + '.sp1_5').setVisible(false);

                $('cpghRep' + row + '.sp_0').setVisible(!chi);
                $('cpghRep' + row + '.sp_1').setVisible(!peng);
                $('cpghRep' + row + '.sp_2').setVisible(!gang);
                $('cpghRep' + row + '.sp_3').setVisible(!hu);
                $('cpghRep' + row + '.sp_4').setVisible(false);
                $('cpghRep' + row + '.sp_5').setVisible(true);

                var pai = $('cpghRep' + row + '.sp_pai');
                var paiName = getPaiNameByRowAndId(2, paiId, true);
                pai.setScale(0.65, 0.65);
                setSpriteFrameByName(pai, paiName, that.getPaiPlist());
                cpg.setVisible(true);
            }
        },
        hideChiPengGangHu: function () {
            $('cpghg').setVisible(false);
            if ($('chiLayer'))
                $('chiLayer').removeFromParent(false);
        },
        sendChiPengGang: function (op, row, paiId, oriPaiId) {
            network.send(4003, {room_id: gameData.roomId, op: op, pai_id: paiId, ori_pai_id: oriPaiId});
        },

        /**
         * 胡牌动画
         * @private
         * */
        _huAnimation: function (row, hu_type) {
            var aniName = '';
            switch (hu_type) {
                case majiang.HuType.ZiMo:
                    aniName = "zimo";
                    playEffect('vzimo', position2sex[row]);
                    break;
                case majiang.HuType.DianPao:
                    aniName = "hu";
                    playEffect('vhu', position2sex[row]);
                    break;
                case majiang.HuType.WangDiao:
                case majiang.HuType.WangDiaoWang:
                    aniName = "wangdiao";
                    playEffect('vwangdiao', position2sex[row]);
                    break;
                case majiang.HuType.WangChuang:
                case majiang.HuType.WangChuangWang:
                    aniName = "wangchuang";
                    playEffect('vwangchuang', position2sex[row]);
                    break;
                default:
                    break;
            }
            network.stop();
            if (aniName !== '') {
                var infoNode = $('info_n' + row);
                infoNode.removeAllChildren();
                this.showActAnimation(infoNode, aniName, false);
                /*
                playAnimScene(infoNode, ani_json, 0, 0, false, function () {
                    infoNode.removeAllChildren();
                });
                 */
                setTimeout(function () {
                    network.start();
                }, 2000);
            } else {
                network.start();
            }
        },

        playChiPengGangHuAnim: function (row, op, is_zimo) {
            var aniName = is_zimo ? 'zimo' : {
                1: 'chi',
                2: 'peng',
                3: 'gang',
                4: 'hu',
                6: 'ting'
            }[op];

            var infoNode = $('info_n' + row);
            if (infoNode.children.length != 0) {
                infoNode.removeAllChildren();
            }

            this.showActAnimation(infoNode, aniName, false);
            /*
            playAnimScene(infoNode, majiang.res[ccsname], 0, 0, false, function () {
                infoNode.removeAllChildren();
            });
             */
        },
        setReplayProgress: function (cur, total) {
            var progress = cur / total * 100;
            this.showTip('回放进度: ' + progress.toFixed(1) + '%', false);
        },
        setAllPai4Replay: function (data) {
            for (var uid in data)
                if (data.hasOwnProperty(uid)) {
                    var row = uid2position[uid];
                    var paiArr = data[uid]['pai_arr'];
                    this.setPaiArrOfRow(row, paiArr, (row != 2), false);

                    var duiArr = data[uid]['dui_arr'];
                    for (var j = 0; j < duiArr.length; j++) {
                        var dui = duiArr[j];
                        if (dui.type == 1) this.setGChi(row, j, dui['pai_arr']);
                        if (dui.type == 2) this.setGPeng(row, j, dui['pai_arr'][0]);
                        if (dui.type == 3) this.setGGang(row, j, dui['pai_arr'][0], dui['pai_arr'][0]);
                        if (dui.type == 4) this.setGGang(row, j, dui['pai_arr'][0], 0);
                        if (dui.type == 5) this.setGHide(row, j);
                    }
                    for (; j < 4 && $('row' + row + '.g' + j); j++)
                        $('row' + row + '.g' + j).setVisible(false);

                    if ($('row' + row + '.g' + 0).isVisible() == 0) {
                        $('row' + row + '.a' + 0).setPosition(posConf.paiA0PosBak[row]);
                    }

                    var usedArr = data[uid]['used_arr'];
                    for (var j = 0; j < 24; j++) {
                        var pai = $('row' + row + '.c0.b' + j);
                        if (pai)
                            pai.setVisible(false);
                        else
                            break;
                    }
                    for (var j = 0; j < usedArr.length; j++) {
                        this.addUsedPai(row, usedArr[j]);
                    }

                    this.recalcPos(row);
                }
        },
        chiPengGangHu: function (op, row, paiId, fromRow, data) {

            if (isReplay) {
                var node = $('cpghRep' + row + '.sp_' + (op - 1));

                var touch_node = new cc.Node();
                $('cpghRep' + row).addChild(touch_node);
                touch_node.setPosition(node.getPositionX(), node.getPositionY() - 40);

                var touch_sp0 = new cc.Sprite(majiang.res.touch0_png);
                var touch_sp1 = new cc.Sprite(majiang.res.touch1_png);
                touch_node.addChild(touch_sp0);
                touch_node.addChild(touch_sp1);
                touch_sp1.setVisible(false);

                touch_node.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(function () {
                    touch_sp0.setVisible(false);
                    touch_sp1.setVisible(true);
                }), cc.delayTime(0.818), cc.callFunc(function () {
                    touch_node.removeFromParent();
                    $('cpghRep' + row).setVisible(false);
                })));
            }

            var j;
            for (j = 0; j < 4; j++) {
                var g = $('row' + row + '.g' + j);
                if (!g || !$('row' + row + '.g' + j).isVisible())
                    break;
            }

            var paiArr = this.getPaiArr();

            if (op == OP_CHI) {
                var oriPaiId = data['ori_pai_id'];
                this.setGChi(row, j, paiId, oriPaiId);
                hasChupai = false;
                this.removeOneTopUsedPai(fromRow);
                this.playChiPengGangHuAnim(row, op);
                playEffect('vchi', position2sex[row]);
            } else if (op == OP_PENG || op == OP_GANG) {
                var duiArr = (data['dui_arr'] || []);
                var isJiagang = (data['is_jiagang'] || 0);

                if (op == OP_PENG) {
                    this.setGPeng(row, j, paiId);
                    //动画
                    if (row == 2) {
                        var pai_peng = [], anim_pai_peng = [];
                        for (var i = 0; i < 3; i++) {
                            var _pai = this.getGPai(row, j, i);
                            pai_peng.push(_pai);
                            var _animpai = duplicateNode(_pai,true);
                            this.addChild(_animpai);
                            anim_pai_peng.push(_animpai);
                            _pai.setVisible(false);
                        }
                        anim_pai_peng[0].setPosition(400, 150);
                        anim_pai_peng[1].setPosition(640, 150);
                        anim_pai_peng[2].setPosition(880, 150);
                        setTimeout(function () {
                            for (var i = 0; i < 3; i++) {
                                (function (_animpeng, _peng, k) {
                                    _animpeng.runAction(cc.sequence(
                                        cc.moveBy(0.15, k == 0
                                                        ? 180
                                                        : (k == 2
                                                           ? -180
                                                           : 0), 0).easing(cc.easeIn(2)),
                                        cc.delayTime(0.85),
                                        cc.moveTo(0.2,
                                            $('row2').getPositionX() + $('row2.g' + j).getPositionX() + _peng.getPositionX(),
                                            $('row2').getPositionY() + $('row2.g' + j).getPositionY() + _peng.getPositionY()),
                                        cc.callFunc(function () {
                                            _peng.setVisible(true);
                                            _animpeng.removeFromParent();
                                        })
                                    ));
                                })(anim_pai_peng[i], pai_peng[i], i);
                            }
                        }, 0);
                    }
                    _.remove(paiArr, function (n) {
                        return n == paiId;
                    });
                    hasChupai = false;
                    this.removeOneTopUsedPai(fromRow);
                    this.playChiPengGangHuAnim(row, op);
                    playEffect('vpeng', position2sex[row]);
                }
                else if (op == OP_PENG || op == OP_GANG) {
                    var isAngang = (row == fromRow && !isJiagang);
                    var upPaiId = paiId;
                    var downPaiId = (isAngang
                                     ? 0
                                     : paiId);

                    if (duiArr)
                        this.setDuiArr(row, duiArr);
                    else {
                        if (isAngang || !isJiagang) {   // angang or minggang
                            this.setGGang(row, j, upPaiId, downPaiId);
                        }
                        else if (isJiagang) {
                            this.setGJiaGang(row, paiId);
                        }
                    }

                    if (row != fromRow)
                        this.removeOneTopUsedPai(fromRow);

                    _.remove(paiArr, function (n) {
                        return n == paiId;
                    });

                    hasChupai = false;
                    if (row == 2 || isJiagang)
                        hasChupai = true;

                    this.playChiPengGangHuAnim(row, op, false, isAngang);
                    playEffect(isAngang
                               ? 'vangang'
                               : 'vgang', position2sex[row]);
                }

                this.hideChiPengGangHu();

                if (!isJiagang && !duiArr)
                    $('row' + row + '.g' + j).setVisible(true);
            }
            else if (op == OP_HU) {
                var hu_type = data['hu_type'];
                var is_zimo = (hu_type === majiang.HuType.ZiMo)
                    || (hu_type === majiang.HuType.WangDiao)
                    || (hu_type === majiang.HuType.WangDiaoWang)
                    || (hu_type === majiang.HuType.WangChuang)
                    || (hu_type === majiang.HuType.WangChuangWang);
                if (fromRow == 2) {
                    this.hideChiPengGangHu();
                }
                if (!is_zimo) {
                    this.removeOneTopUsedPai(fromRow, paiId);
                }
                // this.playChiPengGangHuAnim(row, op, hu_type);
                this._huAnimation(row, hu_type);
                // playEffect(is_zimo ? 'vzimo' : 'vhu', position2sex[row]);
            } else {
                return;
            }

            this.playerOnloneStatusChange(row, false);

            var _paiArr = (data['pai_arr'] || []);
            var liangPaiArr = (data['liang_pai_arr'] || []);
            var paiCnt = (data['pai_cnt'] || 0);
            var n = paiCnt - _paiArr.length;
            for (var i = 0; i < n; i++)
                _paiArr.push(0);
            if (op == OP_HU) {
                curHuPaiId = paiId;
            }
            if (op !== OP_HU) {
                this.setPaiArrOfRow(row, _paiArr, (row != 2), (op != OP_HU), liangPaiArr, false, curHuPaiId);
            }

            if (op == OP_HU && _.isObject(data['player'])) {
                var playerMap = data['player'];
                for (var uid in playerMap) {
                    var tRow = uid2position[uid];
                    var tPaiArr = playerMap[uid]['pai_arr'];
                    var tDuiArr = playerMap[uid]['dui_arr'];
                    if (tRow != 2) {
                        for (var i = 0; i < tPaiArr.length; i++)
                            tPaiArr[i] = 0;
                    }
                    this.setDuiArr(tRow, tDuiArr);
                    this.setPaiArrOfRow(tRow, tPaiArr, (tRow != 2), (tRow != 2));
                    this.recalcPos(tRow);
                }
            }

            if (op != OP_HU) {
                this.setPai(row, 13, 0);
                this.getPai(row, 13).runAction(cc.fadeOut(0));
            }
            this.recalcPos(row);
            this.checkPaiAmount();
        },

        fapai: function (paiArr) {
            paiArr = this._sort(paiArr, [0]);

            forRows(function (i) {
                for (var j = 0; j < paiArr.length; j++)
                    this.setPai(i, j, (i == 2
                                       ? paiArr[j]
                                       : 0), (i != 2), (i != 2));
                for (; j < 14; j++)
                    this.setPai(i, j, 0, (i != 2), (i != 2), false);
            });
            this.setPai(2, 13, 0, false, false, this.isMyTurn());
            forRows(function (i) {
                for (var j = 0; j < 13; j++) {
                    this.getPai(i, j).setVisible(true);
                    this.getPai(i, j).runAction(
                        cc.sequence(cc.delayTime(j * FAPAI_ANIM_DELAY), cc.fadeIn(FAPAI_ANIM_DURATION))
                    );
                    var userData = this.getPai(i, j).getUserData();
                    userData.isUp = false;
                    userData.isUpping = false;
                    userData.isDowning = false;
                }
                this.getPai(i, 13).setVisible(false);
                this.getPai(i, 13).getUserData().isUp = false;
                this.getPai(i, 13).isUp = false;
                this.getPai(i, 13).isUpping = false;
                this.getPai(i, 13).isDowning = false;
                this.recalcPos(i);
            });
            this.enableChuPai();

            if ($('info0.liang')) $('info0.liang').setVisible(false);
            if ($('info1.liang')) $('info1.liang').setVisible(false);
            if ($('info2.liang')) $('info2.liang').setVisible(false);
            if ($('info3.liang')) $('info3.liang').setVisible(false);
            hideGangStep = 0;
            liangStep = 0;
            afterLianging = false;
            curHuPaiId = 0;
            this.HuCardTip(null, 0, false);
        },
        jiesuan: function (data) {
            var that = this;
            that.jieSuanData = data;
            var myScore = 0;
            var players = data.players;
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var uid = player['uid'];

                gameData.players[position2playerArrIdx[uid2position[uid]]].total_score = player['total_score'];
                $('info' + uid2position[uid] + '.lb_score').setString(player['total_score']);

                if (uid == gameData.uid) {
                    myScore = player['score'];
                    continue;
                }

                var row = uid2position[uid];
                var paiArr = player['pai_arr'];
                if (data['hu_type'] == 2 && player['hu'])
                    this.setPaiArrOfRow(uid2position[uid], paiArr, (row != 2), false, [], false, curHuPaiId);
                else
                    this.setPaiArrOfRow(uid2position[uid], paiArr, (row != 2), false);
            }
        },

        /**
         * 打开结算
         * @private
         * */
        _openJiesuanLayer: function () {
            var that = this;
            if (this._jiesuan_data) {
                var is_winner = false;
                var players = this._jiesuan_data.players || [];
                for (var i = 0; i < players.length; i++) {
                    if (players[i] && players[i]['uid'] === gameData.uid) {
                        if (players[i]['score'] > 0) {
                            is_winner = true;
                            break;
                        }
                    }
                }
                //todo:warnning 代码屏蔽问题
                network.stop([4009]);
                var jiesuanLayer = new majiang.JiesuanLayer(that._jiesuan_data);
                if (cc.sys.isObjectValid(that)){
                    that.addChild(jiesuanLayer);
                }
                else {
                    jiesuanLayer.removeFromParent();
                    jiesuanLayer = null;
                }
                //playEffect(is_winner ? 'vWin' : 'vLose');
            }
        },
        onJiesuanClose: function (isReady) {
            network.start();
            if (isReady) {
                $('jiesuan_btn_bg').setVisible(false);
                $('btn_zhunbei').setVisible(false);
                $('btn_jixuyouxi').setVisible(false);
                $('btn_chakanjiesuan').setVisible(false);
            } else {
                $('jiesuan_btn_bg').setVisible(true);
                $('btn_jixuyouxi').setVisible(true);
                $('btn_jixuyouxi').setPosition(cc.p(800, 360));
                //$('btn_jixuyouxi.Text_5').setString('继续游戏');
                safeShow($('btn_chakanjiesuan'));
                $('timer').setVisible(true);
                //$('timer2').setVisible(true);
                $('timer2x').setVisible(true);
            }
        },
        zongJiesuan: function () {
            var that = this;
            if (!that.RoomResultData) return;
            $('jiesuan_btn_bg').setVisible(false);
            $('btn_zhunbei').setVisible(false);
            $('btn_jixuyouxi').setVisible(false);
            $('btn_chakanjiesuan').setVisible(false);
            that.addChild(new Mahjang_ZongJiesuanLayer(deepCopy(that.RoomResultData)));
            that.RoomResultData = null;
        },
        //点击头像添加
        showPlayerInfoPanel: function (idx) {
            if (window.inReview)
                return;
            if (position2playerArrIdx[idx] >= gameData.players.length)
                return;
            var that = this;
            var playerInfo = gameData.players[position2playerArrIdx[idx]];
            network.send(3018, {cmd: 'queryEmoji',uid: gameData.uid,room_id:gameData.roomId});
            showWindow('PlayerInfoInGameWindow',playerInfo,that);
        },
        playerOnloneStatusChange: function (row, isOffline) {
            if ($('info' + row + '.offline'))
                $('info' + row + '.offline').setVisible(!!isOffline);
        },
        playUrlVoice: function (row, type, content, voice, uid) {
            var url = decodeURIComponent(content);
            var arr = null;
            if (url.indexOf('.aac') >= 0) {
                arr = url.split(/\.aac/)[0].split(/-/);
            } else if (url.indexOf('.spx') >= 0) {
                arr = url.split(/\.spx/)[0].split(/-/);
                // playVoiceByUrl(url);
            }
            mRoom.voiceMap[uid] = null;
            mRoom.voiceMap[uid] = url;
            var duration = arr[arr.length - 1] / 1000;
            window.soundQueue = window.soundQueue || [];
            window.soundQueue.push({url: url, duration: duration, row: row});
            if (window.soundQueue.length > 1) {
            } else {
                this.playVoiceQueue();
            }
        },
        playVoiceQueue: function () {
            var that = this;
            var queue = window.soundQueue[0];
            if (queue && queue.url && queue.duration && _.isNumber(queue.row)) {
                if (queue.url.indexOf('.aac') >= 0) {
                    VoiceUtils.play(queue.url);
                } else if (queue.url.indexOf('.spx') >= 0) {
                    OldVoiceUtils.playVoiceByUrl(queue.url);
                }
                var scale9sprite = this.initQP(queue.row);
                scale9sprite.setContentSize(posConf.ltqpEmojiSize[queue.row]);
                var innerNodes = this.initSpeaker(queue.row, scale9sprite);
                this.qpAction(innerNodes, scale9sprite, queue.duration);
                setTimeout(function () {
                    window.soundQueue.shift();
                    that.playVoiceQueue();
                }, queue.duration * 1000);
                if (cc.sys.isNative)
                    jsb.AudioEngine.pauseAll();
                gameData.voiceStop = true;
            } else {
                gameData.voiceStop = false;
                var nosound = cc.sys.localStorage.getItem('voiceFlag') == 1;
                gameData.voiceFlag = nosound;
                if (cc.sys.isNative) {
                    if (gameData.voiceFlag) {
                        jsb.AudioEngine.pauseAll();
                    } else {
                        jsb.AudioEngine.resumeAll();
                    }
                }
            }
        },
        initQP: function (row) {
            // var scale9sprite = $('info' + row + '.qp');
            // for (var i = (cc.sys.isNative
            //               ? 0
            //               : 1); i < scale9sprite.getChildren().length; i++) {
            //     scale9sprite.getChildren()[i].setVisible(false);
            // }
            // return scale9sprite;
        },
        initSpeaker: function (row, scale9sprite) {
            var map = {};
            var innerNodes = [];
            for (var i = 1; i <= 3; i++) {
                var sp = $('speaker' + i, scale9sprite);
                if (!sp) {
                    sp = new cc.Sprite(res['speaker' + i]);
                    sp.setName('speaker' + i);
                    sp.setPosition(posConf.ltqpVoicePos[row]);
                    scale9sprite.addChild(sp);
                }
                map[i] = sp;
                map[i].setVisible(true);
                innerNodes.push(map[i]);
            }
            map[2].runAction(cc.sequence(cc.fadeOut(0), cc.delayTime(0.25), cc.fadeIn(0.25)).repeatForever());
            map[3].runAction(cc.sequence(cc.fadeOut(0), cc.delayTime(0.50), cc.fadeIn(0.50)).repeatForever());
            return innerNodes;
        },
        qpAction: function (innerNodes, scale9sprite, duration) {
            scale9sprite.stopAllActions();
            scale9sprite.setVisible(true);
            scale9sprite.setOpacity(255);
            scale9sprite.runAction(cc.sequence(cc.delayTime(duration), cc.fadeOut(0.5), cc.callFunc(function () {
                for (var i = 0; i < innerNodes.length; i++)
                    innerNodes[i].setVisible(false);
            })));
        },
        showChat: function (row, type, content, voice, uid) {
            var that = this;

            if (type == 'voice') {
                var url = decodeURIComponent(content);
                if (url && url.split(/\.spx/).length > 2)
                    return;
            }

            if (type == 'voice') {
                this.playUrlVoice(row, type, content, voice, uid);
                return;
            }

            var scale9sprite = $('info' + row + '.qp');
            for (var i = (cc.sys.isNative
                          ? 0
                          : 1); i < scale9sprite.getChildren().length; i++) {
                scale9sprite.getChildren()[i].setVisible(false);
            }

            var duration = 4;
            var innerNodes = [];
            scale9sprite.setCascadeOpacityEnabled(false);
            if (type == 'emoji') {
                scale9sprite.setOpacity(0);
                scale9sprite.setContentSize(posConf.ltqpEmojiSize[row]);
                var sprite = $('info' + row).getChildByName('emoji');
                if (sprite) {
                    sprite.removeFromParent();
                    sprite = null;
                }
                if (!sprite) {
                    sprite = new cc.Sprite();
                    sprite.setName('emoji');
                    sprite.setPosition(posConf.ltqpEmojiPos[row]);
                    $('info' + row).addChild(sprite);
                }
                if (content.indexOf('sp_') == 0) {
                    duration = 5;
                    var name = content.split('_')[1];
                    if (name == 'laotou' || name == 'tuxue') {
                        var psX = sprite.convertToWorldSpace(sprite.getPosition());
                        // cc.log("psXpsXpsX===="+psX.x)
                        if (psX.x > cc.winSize.width / 2) {
                            sprite.setScaleX(-1);
                        }
                    }
                    if (name == 'tuxue' || name == 'chuizhuozi') {
                        var time = 0;
                        if (name == 'chuizhuozi') {
                            time = 2000;
                        }
                        setTimeout(function () {
                            playEffect('vEffect_emoji_' + name);
                        }, time);

                        var emoji = playSpAnimation(name, name + 1, false, null, function () {
                            setTimeout(function () {
                                emoji.removeFromParent(true);
                            }, 10);

                        });
                    } else {
                        var emoji = playSpAnimation(name, name + 1, false, null, function () {
                            setTimeout(function () {
                                emoji.removeFromParent(true);
                            }, 10);
                            playEffect('vEffect_emoji_' + name);
                            var emoji2 = playSpAnimation(name, name + 2, false, null, function () {
                                setTimeout(function () {
                                    emoji2.removeFromParent(true);
                                }, 10);
                            });
                            sprite.addChild(emoji2);
                        });
                    }

                    sprite.addChild(emoji);
                } else {
                    var resPath = res[content];
                    if (resPath) {
                        playAnimScene(sprite, resPath, 0, 0, true, function () {
                            if (sprite) sprite.removeFromParent(true);
                        });
                    } else {
                        try {
                            setSpriteFrameByName(sprite, content, 'emoji');
                        } catch (e) {

                        }

                    }
                }
                sprite.setVisible(true);
                sprite.setOpacity(255);
                innerNodes.push(sprite);
            }
            else if (type == 'text') {
                var text = $('text', scale9sprite);
                if (!text) {
                    text = new ccui.Text();
                    text.setName('text');
                    text.setFontSize(20);
                    text.setTextColor(cc.color(255, 255, 255));
                    text.setAnchorPoint(0, 0.5);
                    text.enableOutline(cc.color(67, 99, 101), 2);
                    scale9sprite.setOpacity(255);
                    scale9sprite.addChild(text);
                }

                text.setString(content);

                var size = scale9sprite.getContentSize();
                size.width = text.getVirtualRendererSize().width + posConf.ltqpRect[row].width / 2;
                text.x = (size.width - text.getVirtualRendererSize().width) / 2 + posConf.ltqpTextDelta[row].x;
                text.y = size.height / 2;
                scale9sprite.setContentSize(size);
                text.setVisible(true);
                innerNodes.push(text);
            }
            else if (type == 'voice') {
                var url = decodeURIComponent(content);
                scale9sprite.setContentSize(posConf.ltqpEmojiSize[row]);
                if (cc.sys.isNative) {
                    var arr = null;
                    if (url.indexOf('.aac') >= 0) {
                        arr = url.split(/\.aac/)[0].split(/-/);
                        VoiceUtils.play(url);
                    } else if (url.indexOf('.spx') >= 0) {
                        arr = url.split(/\.spx/)[0].split(/-/);
                        playVoiceByUrl(url);
                    }
                }

                duration = arr[arr.length - 1] / 1000;
                var map = {};
                for (var i = 1; i <= 3; i++) {
                    var sp = $('speaker' + i, scale9sprite);
                    if (!sp) {
                        sp = new cc.Sprite(res['speaker' + i]);
                        sp.setName('speaker' + i);
                        sp.setPosition(posConf.ltqpVoicePos[row]);
                        scale9sprite.addChild(sp);
                    }
                    map[i] = sp;
                    map[i].setVisible(true);
                    innerNodes.push(map[i]);
                }
                map[2].runAction(cc.sequence(cc.fadeOut(0), cc.delayTime(0.25), cc.fadeIn(0.25)).repeatForever());
                map[3].runAction(cc.sequence(cc.fadeOut(0), cc.delayTime(0.50), cc.fadeIn(0.50)).repeatForever());
            }

            scale9sprite.stopAllActions();
            scale9sprite.setVisible((type == 'emoji')
                                    ? false
                                    : true);
            scale9sprite.setOpacity(255);
            scale9sprite.runAction(cc.sequence(cc.delayTime(duration), cc.fadeOut(0.5), cc.callFunc(function () {
                for (var i = 0; i < innerNodes.length; i++)
                    innerNodes[i].setVisible(false);
            })));
            if (type != 'voice') {
                for (var i = 0; i < innerNodes.length; i++) {
                    var innerNode = innerNodes[i];
                    innerNode.stopAllActions();
                    innerNode.setVisible(true);
                    innerNode.setOpacity(255);
                    //innerNode.setScale(1.5, 1.5);
                    innerNode.runAction(cc.sequence(cc.delayTime(duration), cc.fadeOut(0.5)));
                }
            }
            if (voice && !window.inReview)
                playEffect(voice);
        },
        setZhuang: function (row) {
            $('info0.zhuang').setVisible(false);
            $('info1.zhuang').setVisible(false);
            $('info2.zhuang').setVisible(false);
            $('info3.zhuang').setVisible(false);
            $('info' + row + '.zhuang').setVisible(true);
        },
        setBeforeOnCCSLoadFinish: function (cb) {
            this.beforeOnCCSLoadFinish = cb;
        },
        getBeforeOnCCSLoadFinish: function (cb) {
            return this.beforeOnCCSLoadFinish;
        },
        setAfterGameStart: function (cb) {
            this.afterGameStart = cb;
        },
        setReady: function (uid) {
            try {
                var row = uid2position[uid];
                var ok = $('info' + uid2position[uid] + '.ok');
                if (!ok) {
                    ok = duplicateNode($('info0.ok'),true);
                    ok.setVisible(true);
                    ok.setPosition(cc.p((row == 0 || row == 2)
                                        ? 20
                                        : ((row == 1)
                                           ? 40
                                           : -60), (row == 0)
                                                   ? 20
                                                   : ((row == 1)
                                                      ? 40
                                                      : 20)));
                    if (uid2position[uid] && $('info' + uid2position[uid])) $('info' + uid2position[uid]).addChild(ok);
                }
                if (ok) {
                    ok.setVisible(true);
                }
                if (uid2playerInfo[uid]) {
                    uid2playerInfo[uid]['ready'] = 1;
                }
                this.refreshPlayersStates();
                if (uid == gameData.uid) {
                    $('jiesuan_btn_bg').setVisible(false);
                    $('btn_zhunbei').setVisible(false);
                    $('btn_jixuyouxi').setVisible(false);
                    $('btn_chakanjiesuan').setVisible(false);
                }
            } catch (e) {
                console.log('' + e.toString());
            }
        },
        showToast: function (msg) {
            var toast = $('toast');
            if (!toast) {
                toast = new cc.Sprite(majiang.res.toast_bg_png);
                toast.setName('toast');
                this.addChild(toast);

                var text = new ccui.Text();
                text.setName('text');
                text.setFontSize(30);
                text.setTextColor(cc.color(255, 255, 255));
                text.setPosition(toast.getBoundingBox().width / 2, toast.getBoundingBox().height / 2);
                text.setString(msg);
                toast.setPosition(cc.winSize.width / 2, cc.winSize.height / 2 * 4 / 5);
                toast.addChild(text);
            }
            toast.stopAllActions();
            toast.runAction(cc.sequence(cc.fadeIn(3), cc.fadeOut(0.3)));
            text = toast.getChildByName('text');
            text.runAction(cc.sequence(cc.fadeIn(3), cc.fadeOut(0.3)));
        },
        initWanfa: function () {
            if (!gameData.wanfaDesp)
                return;
            var arr = decodeURIComponent(gameData.wanfaDesp).split(',');
            var topPosY = cc.winSize.height / 2 + 116;

            var sp_wanfa_Pos = cc.p(0, topPosY);
            var sp_wanfa = new cc.Sprite(res.sp_wanfa_png);
            var sp_wanfa_size = cc.size(47, 85);
            sp_wanfa.setPosition(sp_wanfa_Pos);
            sp_wanfa.setAnchorPoint(0, 0);
            this.addChild(sp_wanfa);

            var scale9sprite = new cc.Scale9Sprite(res.sp_picback_png, cc.rect(0, 0, 1, 1), cc.rect(0.25, 0.25, 0.5, 0.5));
            scale9sprite.setName('s9p');
            scale9sprite.setAnchorPoint(0, 1);

            var maxLength = 0;
            var textHeight = 0;
            var fontSize = 25;
            var marginSize = cc.p(11, 5);
            var fontColor = cc.color(254, 245, 92);
            var scale9Height = 0;
            var scale9Width = 0;
            for (var i = 0; i < arr.length; i++) {
                var text = new ccui.Text();
                text.setFontSize(fontSize);
                text.setColor(fontColor);
                text.setAnchorPoint(0, 0);
                text.setString(arr[i]);
                text.setName('text' + i);
                var twidth = text.getVirtualRendererSize().width;
                textHeight = text.getAutoRenderSize().height;
                if (!scale9Height)
                    scale9Height = Math.max(arr.length * (textHeight + marginSize.y) + 3 * marginSize.y, sp_wanfa_size.height);
                text.setPosition(marginSize.x, scale9Height - marginSize.y - (textHeight + marginSize.y) * (i + 1));
                text.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
                scale9sprite.addChild(text);
                maxLength = twidth > maxLength
                            ? twidth
                            : maxLength;
            }

            scale9Width = maxLength + marginSize.x * 2;
            scale9sprite.setPosition(-scale9Width, sp_wanfa_size.height);
            scale9sprite.setPreferredSize(cc.size(scale9Width, scale9Height));
            sp_wanfa.addChild(scale9sprite);

            var pullOrPush = true;
            TouchUtil.setOnclickListener(sp_wanfa, function () {
                //console.log(sp_wanfa.getChildrenCount());
                sp_wanfa.stopAllActions();
                if (pullOrPush)
                    sp_wanfa.runAction(cc.moveTo(0.25, sp_wanfa_Pos.x + scale9Width, sp_wanfa_Pos.y));
                else
                    sp_wanfa.runAction(cc.moveTo(0.25, sp_wanfa_Pos));
                pullOrPush = !pullOrPush;
            });
        },
        showArrow: function (pai, row) {
            this.hideArrow();
            var arrow = pai.getParent().getChildByName('arrow');
            if (!arrow) {
                arrow = new cc.Sprite(majiang.res.arrow_png);
                arrow.setAnchorPoint(0.5, 0);
                arrow.setName('arrow');
                arrow.setLocalZOrder(100);
                pai.getParent().addChild(arrow);
                var duration = 0.8;
                arrow.setOpacity(168);
            }
            arrow.setVisible(true);
            var arrowrot = [180, 270, 0, 90];
            if (row == 0) {
                arrow.setPosition(pai.getPosition().x, pai.getPosition().y - 35);
            }
            else if (row == 1) {
                arrow.setPosition(pai.getPosition().x - 40, pai.getPosition().y + 10);
            }
            else if (row == 2) {
                arrow.setPosition(pai.getPosition().x, pai.getPosition().y + 30);
            }
            else if (row == 3) {
                arrow.setPosition(pai.getPosition().x + 25, pai.getPosition().y + 5);
            }

            arrow.setRotation(arrowrot[row]);
            if (row == 0 || row == 2) {
                arrow.runAction(cc.sequence(cc.spawn(cc.moveBy(duration, 0, +16), cc.fadeTo(duration, 255))
                    , cc.spawn(cc.moveBy(duration, 0, -16), cc.fadeTo(duration, 168))).repeatForever());
            }
            else if (row == 1 || row == 3) {
                arrow.runAction(cc.sequence(cc.spawn(cc.moveBy(duration, +16, 0), cc.fadeTo(duration, 255))
                    , cc.spawn(cc.moveBy(duration, -16, 0), cc.fadeTo(duration, 168))).repeatForever());
            }
        },
        setLiang: function (liang) {
            lianging = liang;
            return;
            var that = this;
            if (liang) {
                lianging = true;
                for (var i = 0; i < 14; i++) {
                    var pai = that.getPai(2, i);
                    var userData = pai.getUserData();
                    if (userData.pai) {
                        userData.isLiang = false;
                        Filter.grayMask(pai);
                    }
                }
                $('btn_queding').setVisible(true);
                $('btn_quxiao').setVisible(true);
            }
            else {
                $('btn_queding').setVisible(false);
                $('btn_quxiao').setVisible(false);
                that.hideTip();
                lianging = false;
            }
        },
        showTip: function (content, isShake) {
            isShake = _.isUndefined(isShake)
                      ? true
                      : isShake;
            var scale9sprite = $('top_tip');
            if (!(scale9sprite instanceof cc.Scale9Sprite)) {
                var newScale9sprite = new cc.Scale9Sprite(majiang.res.round_rect_91_png_mj, cc.rect(0, 0, 91, 32), cc.rect(46, 16, 1, 1));
                newScale9sprite.setName('top_tip');
                scale9sprite.setAnchorPoint(0.5, 0.5);
                newScale9sprite.setPosition(scale9sprite.getPosition());
                scale9sprite.getParent().addChild(newScale9sprite);
                var lb = $('top_tip.lb_tip');

                text = new ccui.Text();
                text.setName('lb_tip');
                text.setFontSize(lb.getFontSize());
                text.setTextColor(lb.getTextColor());
                text.enableOutline(cc.color(38, 38, 38), 1);
                newScale9sprite.addChild(text);

                lb.removeFromParent(true);
                scale9sprite.removeFromParent(true);
                scale9sprite = newScale9sprite;
            }
            var text = $('top_tip.lb_tip');
            text.setString(content);
            var size = cc.size(text.getVirtualRendererSize().width + 35, scale9sprite.getContentSize().height);
            text.setPosition((text.getVirtualRendererSize().width + 35) / 2, scale9sprite.getContentSize().height / 2);
            scale9sprite.setContentSize(size);
            scale9sprite.setScale(1.2);
            scale9sprite.setVisible(true);
            if (isShake)
                scale9sprite.runAction(cc.sequence(cc.scaleTo(0.2, 1.4), cc.scaleTo(0.2, 1.2)));
        },
        hideTip: function () {
            if (!isReplay)
                $('top_tip').setVisible(false);
        },
        hideArrow: function () {
            for (var i = 0; i < 4; i++) {
                var arrow = $('row' + i + '.c0.arrow');
                if (arrow)
                    arrow.removeFromParent(true);
            }
        },
        liangAllPai: function () {
            for (var i = 0; i < 14; i++) {
                var pai = this.getPai(2, i);
                var userData = pai.getUserData();
                if (userData.pai) {
                    userData.isLiang = true;
                    Filter.remove(pai);
                }
            }
        },
        selectHideGangCb: function () {
            network.send(4015, {room_id: gameData.roomId, hided_gang_arr: hidedGangArr});
        },
        throwDice: function (title, dice, paiIdA, paiIdB, cb) {
            var that = this;
            title = title || '';
            if (dice < 1 || dice > 6)
                return;
            var layer = that.throwDiceLayer;
            if (!layer) {
                var scene = ccs.load(res.ThrowDice_json);
                layer = scene.node;
                layer.setName('throwDice');
                layer.retain();
                that.throwDiceLayer = layer;
            }
            var paiA = $('root.a0', layer);
            var paiB = $('root.a1', layer);
            paiA.setVisible(false);
            paiB.setVisible(false);
            that.addChild(layer);
            $('root.lb_title', layer).setString(title);
            playThrowDice($('root.dice1', layer), Math.floor(Math.random() * 6) + 1);
            playThrowDice($('root.dice', layer), dice, function () {
                var paiAName = getPaiNameByRowAndId(2, paiIdA, true, false);
                var paiBName = getPaiNameByRowAndId(2, paiIdB, true, false);
                setSpriteFrameByName(paiA, paiAName,that.getPaiPlist());
                setSpriteFrameByName(paiB, paiBName, that.getPaiPlist());
                paiA.setVisible(true);
                paiB.setVisible(true);
                setTimeout(function () {
                    layer.removeFromParent(false);
                    if (cb)
                        cb();
                }, 2600);
            });
        },
        throwDice1: function (dice, paiIdA, cb) {
            var that = this;
            if (dice < 1 || dice > 6)
                return;
            var layer = that.throwDiceLayer;
            if (!layer) {
                var scene = ccs.load(res.ThrowDiceforLeiyang_json);
                layer = scene.node;
                layer.setName('throwDice');
                layer.retain();
                that.throwDiceLayer = layer;
            }
            var paiA = $('root.a0', layer);
            paiA.setVisible(false);
            that.addChild(layer);
            playThrowDice($('root.dice1', layer), Math.floor(Math.random() * 6) + 1);
            playThrowDice($('root.dice', layer), dice, function () {
                var paiAName = getPaiNameByRowAndId(2, paiIdA, true, false);
                setSpriteFrameByName(paiA, paiAName,that.getPaiPlist());
                paiA.setVisible(true);
                setTimeout(function () {
                    layer.removeFromParent(false);
                    if (cb)
                        cb();
                }, 2600);
            });
        },
        showChiLayer: function (paiId, cb) {
            var that = this;
            // var paiArr = paiArrBak[row] || that.getPaiArr();
            var paiArr = that.getPaiArr();
            paiArr.push(paiId);
            var arr = [
                [paiId - 2, paiId - 1, paiId],
                [paiId - 1, paiId, paiId + 1],
                [paiId, paiId + 1, paiId + 2]
            ];
            var posibleIdxArr = [];
            for (var i = 0; i < arr.length; i++) {
                var a = arr[i][0];
                var b = arr[i][1];
                var c = arr[i][2];
                if (isSameColor(a, b) && isSameColor(a, c) &&
                    paiArr.indexOf(a) >= 0 && paiArr.indexOf(b) >= 0 && paiArr.indexOf(c) >= 0)
                    posibleIdxArr.push(i);
            }
            if (posibleIdxArr.length == 1) {
                cb(arr[posibleIdxArr[0]][1], paiId);
                // that.sendChiPengGang(OP_CHI, 2, arr[posibleIdxArr[0]][1], paiId);
                that.hideChiPengGangHu();
            }
            else if (posibleIdxArr.length > 1) {
                var layer = that.chiLayer;
                if (!layer) {
                    var scene = ccs.load(majiang.res.ChiPanel_json);
                    layer = scene.node;
                    layer.setName('chiLayer');
                    layer.retain();
                    that.chiLayer = layer;
                }
                that.addChild(layer);

                $('root.g0', layer).setVisible(posibleIdxArr.length >= 1);
                $('root.g1', layer).setVisible(posibleIdxArr.length >= 2);
                $('root.g2', layer).setVisible(posibleIdxArr.length >= 3);

                var fun = function (node) {
                    var parentName = node.getParent().getName();
                    var userData = $('root.' + parentName + '.' + 1, layer).getUserData();
                    var _paiId = userData.pai;
                    var paiId = userData.ori_pai_id;
                    cb(_paiId, paiId);
                    // that.sendChiPengGang(OP_CHI, 2, _paiId, paiId);
                    that.hideChiPengGangHu();
                    layer.removeFromParent(false);
                };

                for (var i = 0; i < posibleIdxArr.length; i++) {
                    for (var j = 0; j < 3; j++) {
                        var pai = $('root.g' + i + '.' + j, layer);
                        var _paiId = arr[posibleIdxArr[i]][j];
                        var paiName = getPaiNameByRowAndId(2, _paiId, true, false);
                        pai.setUserData({pai: _paiId, ori_pai_id: paiId});
                        setSpriteFrameByName(pai, paiName, that.getPaiPlist());

                        TouchUtil.setOnclickListener(pai, fun);
                    }
                }

                TouchUtil.setOnclickListener($('root.btn_close', layer), function () {
                    layer.removeFromParent();
                });
                TouchUtil.setOnclickListener($('root', layer), function () {
                    // layer.removeFromParent();
                });
            }
        },
        playEffect: function (filename, sex) {
            playEffect(filename, sex);
        },
        setHuTipVisible: function (visible) {
            for (var i = 0; i < 14; i++) {
                var cardSprite = this.getPai(2, i);
                if (cardSprite.getChildByName('hucardSprite')) {
                    cardSprite.getChildByName('hucardSprite').stopAllActions();
                    cardSprite.getChildByName('hucardSprite').setVisible(visible);
                }
            }
        },
        showChangeScore: function (row, score) {
            if (!score) {
                return;
            }
            var txt = new cc.LabelBMFont(score > 0
                                         ? '+' + score
                                         : score, score < 0
                                                  ? res.score_blue_fnt
                                                  : res.score_yellow_fnt);
            var change_sroce_node = $('info' + row + '.change_sroce_node');
            change_sroce_node.addChild(txt);
            txt.runAction(
                cc.sequence(
                    cc.moveBy(1.5, cc.p(0, 30)),
                    cc.callFunc(function () {
                        txt.removeFromParent(true);
                    })
                )
            );
        },
        isShaGui: function () {
            return gameData.wanfaDesp && gameData.wanfaDesp.indexOf('不杀鬼') >= 0;
            // if(gameData.wanfaDesp && gameData.wanfaDesp.indexOf("杀鬼") >= 0){
            //     return false;
            // }
            // return true;
        },
        HuCardTip: function (showdata, posx, isVisible) {
            var hupaitip = this.getChildByName('hupaitip');
            if (!isVisible && hupaitip) {
                hupaitip.setVisible(isVisible);
                return;
            }
            if (showdata == null) {
                for (var i = 0; i < 14; i++) {
                    var pai = this.getPai(2, i);
                    var userData = pai.getUserData();
                    userData.hucards = null;
                }
                return;
            }
            var tiplength = showdata.length;
            if (hupaitip) {
                hupaitip.setVisible(true);
                hupaitip.setContentSize(cc.size(120 + 120 * tiplength, 80));
                //设置位置
                posx = posx + 40;
                if (posx + hupaitip.getContentSize().width / 2 > maLayer.getContentSize().width) {
                    posx = maLayer.getContentSize().width - hupaitip.getContentSize().width / 2 - 20;
                } else if (posx - hupaitip.getContentSize().width / 2 < 0) {
                    posx = hupaitip.getContentSize().width / 2 + 20;
                }
                hupaitip.setPositionX(posx);
                for (var i = 0; i < 9; i++) {
                    var card = hupaitip.getChildByName('card' + (i + 1));
                    var fantext = hupaitip.getChildByName('fantext' + (i + 1));
                    var fannum = hupaitip.getChildByName('fannum' + (i + 1));
                    var zhangtext = hupaitip.getChildByName('zhangtext' + (i + 1));
                    var zhangnum = hupaitip.getChildByName('zhangnum' + (i + 1));
                    if (tiplength > i) {
                        //card
                        card.setVisible(true);
                        var paiName = getPaiNameByRowAndId(2, showdata[i][0], true, true);
                        setSpriteFrameByName(card, paiName, this.getPaiPlist());
                        card.setPosition(cc.p(-5 + 120 * (i + 1), hupaitip.getContentSize().height / 2));
                        fantext.setVisible(true);
                        fantext.setPosition(cc.p(60 + 120 * (i + 1), 60));
                        fannum.setVisible(true);
                        fannum.setPosition(cc.p(40 + 120 * (i + 1), 60));
                        fannum.setString(showdata[i][1]);
                        zhangtext.setVisible(true);
                        zhangtext.setPosition(cc.p(60 + 120 * (i + 1), 20));
                        zhangnum.setVisible(true);
                        zhangnum.setString(showdata[i][2]);
                        zhangnum.setPosition(cc.p(40 + 120 * (i + 1), 20));
                    } else {
                        card.setVisible(false);
                        fantext.setVisible(false);
                        fannum.setVisible(false);
                        zhangtext.setVisible(false);
                        zhangnum.setVisible(false);
                    }
                }
            } else {
                var hupaitip = new cc.Scale9Sprite(majiang.res.toast_bg_png, null, cc.rect(10, 10, 10, 10));
                hupaitip.setName('hupaitip');
                hupaitip.setAnchorPoint(cc.p(0.5, 0));
                hupaitip.setContentSize(cc.size(120 + 120 * tiplength, 80));
                hupaitip.setPosition(cc.p(maLayer.getContentSize().width - 20, 172));
                maLayer.addChild(hupaitip);
                //设置位置
                posx = posx + 40;
                if (posx + hupaitip.getContentSize().width / 2 > maLayer.getContentSize().width) {
                    posx = maLayer.getContentSize().width - hupaitip.getContentSize().width / 2 - 20;
                } else if (posx - hupaitip.getContentSize().width / 2 < 0) {
                    posx = hupaitip.getContentSize().width / 2 + 20;
                }
                hupaitip.setPositionX(posx);

                var huSprite = new cc.Sprite(majiang.res.hupaitip_hu_png);
                huSprite.setPosition(cc.p(40, hupaitip.getContentSize().height / 2));
                hupaitip.addChild(huSprite);
                for (var i = 0; i < 9; i++) {
                    //card
                    var card = new cc.Sprite();
                    card.setScale(0.88);
                    card.setName('card' + (i + 1));
                    card.setPosition(cc.p(-5 + 120 * (i + 1), hupaitip.getContentSize().height / 2));
                    hupaitip.addChild(card);

                    var fantext = new ccui.Text();
                    fantext.setString('番');
                    fantext.setName('fantext' + (i + 1));
                    fantext.setFontSize(20);
                    fantext.setTextColor(cc.color(0, 255, 0));
                    fantext.enableOutline(cc.color(38, 38, 38), 1);
                    fantext.setPosition(cc.p(60 + 120 * (i + 1), 60));
                    hupaitip.addChild(fantext);
                    var fannum = new ccui.Text();
                    fannum.setName('fannum' + (i + 1));
                    fannum.setFontSize(20);
                    fannum.setTextColor(cc.color(255, 255, 0));
                    fannum.enableOutline(cc.color(38, 38, 38), 1);
                    fannum.setPosition(cc.p(40 + 120 * (i + 1), 60));
                    hupaitip.addChild(fannum);
                    var zhangtext = new ccui.Text();
                    zhangtext.setString('张');
                    zhangtext.setName('zhangtext' + (i + 1));
                    zhangtext.setFontSize(20);
                    zhangtext.setTextColor(cc.color(0, 255, 0));
                    zhangtext.enableOutline(cc.color(38, 38, 38), 1);
                    zhangtext.setPosition(cc.p(60 + 120 * (i + 1), 20));
                    hupaitip.addChild(zhangtext);
                    var zhangnum = new ccui.Text();
                    zhangnum.setName('zhangnum' + (i + 1));
                    zhangnum.setFontSize(20);
                    zhangnum.setTextColor(cc.color(255, 255, 0));
                    zhangnum.enableOutline(cc.color(38, 38, 38), 1);
                    zhangnum.setPosition(cc.p(40 + 120 * (i + 1), 20));
                    hupaitip.addChild(zhangnum);
                    if (tiplength > i) {
                        card.setVisible(true);
                        var paiName = getPaiNameByRowAndId(2, showdata[i][0], true, true);
                        setSpriteFrameByName(card, paiName, this.getPaiPlist());
                        fantext.setVisible(true);
                        fannum.setVisible(true);
                        fannum.setString(showdata[i][1]);
                        zhangtext.setVisible(true);
                        zhangnum.setVisible(true);
                        zhangnum.setString(showdata[i][2]);
                    } else {
                        card.setVisible(false);
                        fantext.setVisible(false);
                        fannum.setVisible(false);
                        zhangtext.setVisible(false);
                        zhangnum.setVisible(false);
                    }
                }
            }
        },
        playShaGuiAnim: function (row) {
            // var bg = new cc.Node();
            var textureName = 's_sha.png';
            // if ($("info" + row + ".change_sroce_node").children().length != 0)
            //     $("info" + row + ".change_sroce_node").removeAllChildren();
            var sprite = new cc.Sprite(res['textureName']);
            // bg.addChild(sprite);
            // $('info_n' + row).addChild(bg);
            this.addChild(sprite);
            sprite.setLocalZOrder(2000);
            sprite.setPosition($('info_n' + row).getPosition());
            sprite.setScale(0, 0);
            var duraction = 1;
            sprite.runAction(cc.sequence(
                cc.scaleTo(duraction, 1.5, 1.5).easing(cc.easeExponentialOut())
                , cc.spawn(
                    cc.scaleTo(0.1, 0.80, 0.80)
                    , cc.fadeOut(0.1)
                )
            ));
        },
        playguipaiAnim: function (row) {
            // var bg = new cc.Node();
            var textureName = 's_guipai.png';
            // if ($("info" + row + ".change_sroce_node").children().length != 0)
            //     $("info" + row + ".change_sroce_node").removeAllChildren();
            var sprite = new cc.Sprite(res[textureName]);
            // bg.addChild(sprite);
            // $('info_n' + row).addChild(bg);
            this.addChild(sprite);
            sprite.setLocalZOrder(2000);
            sprite.setPosition($('info_n' + row).getPosition());
            sprite.setScale(0, 0);
            var duraction = 1;
            sprite.runAction(cc.sequence(
                cc.scaleTo(duraction, 1.5, 1.5).easing(cc.easeExponentialOut())
                , cc.spawn(
                    cc.scaleTo(0.1, 0.80, 0.80)
                    , cc.fadeOut(0.1)
                )
            ));
        },
        ishongzhongzuogui: function () {
            return gameData.wanfaDesp && gameData.wanfaDesp.indexOf('红中做鬼') >= 0;
        },
        sortPaiArr: function (paiArr, row, liangPaiArr, huPaiId) {
            var _paiArr = deepCopy(paiArr);
            if (row == 2)
                _.pull(_paiArr, 0);
            _paiArr.sort(compareTwoNumbers);
            if (mapId == MAP_ID_LEIYANG || mapId == MAP_ID_LEIYANGHONGZHONG) {
                var oldSize = _paiArr.length;
                _.pull(_paiArr, laiziPaiId);
                if (_paiArr.length != oldSize) {
                    var t = _paiArr.length;
                    for (var j = 0; j < oldSize - t; j++)
                        _paiArr.splice(0, 0, laiziPaiId);
                }
            }

            if (huPaiId) {
                var idx = _paiArr.indexOf(huPaiId);
                if (idx >= 0) {
                    _paiArr.splice(idx, 1);
                    _paiArr.push(huPaiId);
                }
            }
            return _paiArr;
        },

        hideControlBtns: function () {
            // $('chat').setVisible(false);
            $('btn_control_btns').setFlippedY(true);
        },

        showControlBtns: function () {
            $('chat').setVisible(true);
        },

        changeBtnStatus: function () {
            $('chat').setVisible(!$('chat').isVisible());
            $('btn_control_btns').setFlippedY(!$('btn_control_btns').isFlippedY());
        },
        showGuiPanel: function () {
            var laiziPanel = $('laizi_panel');
            if (laiziPanel) {
                $('laizi_panel.fanpai_bg.pai').setScale(0);
                $('laizi_panel.fanpai_bg.pai').setVisible(true);
                $('laizi_panel.fanpai_bg.pai').runAction(cc.scaleTo(.5, 0.7, 0.7));

            }
        },
        hideGuiPanel: function () {
            var laiziPanel = $('laizi_panel');
            if (laiziPanel) {
                $('laizi_panel.fanpai_bg.pai').setScale(0);
                $('laizi_panel.fanpai_bg.pai').setVisible(false);

            }
        },
        getRowByUid: function (uid) {
            return uid2position[uid];
        },

        playCoinFlyAnimOfHu: function (row) {
            var head0 = $('info0');
            var head1 = $('info1');
            var head2 = $('info2');
            var head3 = $('info3');
            if (gameData.playerNum == 4) {
                switch (row) {
                    case 0:
                        this.playCoinsFlyAnim(head1, head0, 10);
                        this.playCoinsFlyAnim(head2, head0, 10);
                        this.playCoinsFlyAnim(head3, head0, 10);
                        break;
                    case 1:
                        this.playCoinsFlyAnim(head0, head1, 10);
                        this.playCoinsFlyAnim(head2, head1, 10);
                        this.playCoinsFlyAnim(head3, head1, 10);
                        break;
                    case 2:
                        this.playCoinsFlyAnim(head0, head2, 10);
                        this.playCoinsFlyAnim(head1, head2, 10);
                        this.playCoinsFlyAnim(head3, head2, 10);
                        break;
                    case 3:
                        this.playCoinsFlyAnim(head0, head3, 10);
                        this.playCoinsFlyAnim(head1, head3, 10);
                        this.playCoinsFlyAnim(head2, head3, 10);
                        break;
                    default:
                        break;
                }
            } else if (gameData.playerNum == 3) {
                switch (row) {
                    case 1:
                        this.playCoinsFlyAnim(head2, head1, 10);
                        this.playCoinsFlyAnim(head3, head1, 10);
                        break;
                    case 2:
                        this.playCoinsFlyAnim(head1, head2, 10);
                        this.playCoinsFlyAnim(head3, head2, 10);
                        break;
                    case 3:
                        this.playCoinsFlyAnim(head1, head3, 10);
                        this.playCoinsFlyAnim(head2, head3, 10);
                        break;
                    default:
                        break;
                }
            } else {
                switch (row) {

                    case 0:
                        this.playCoinsFlyAnim(head2, head0, 10);
                        break;
                    case 2:
                        this.playCoinsFlyAnim(head0, head2, 10);
                        break;

                    default:
                        break;
                }
            }


        },
        //金币转移的特效
        playCoinsFlyAnim: function (beginNode, endNode, count) {
            playEffect('vGold');
            var beginPos = cc.p(0, 0);
            if (beginNode) beginPos = beginNode.getPosition();//beginNode.convertToWorldSpace(beginNode.getPosition());
            var endPos = cc.p(0, 0);
            if (endNode) endPos = endNode.getPosition();//endNode.convertToWorldSpace(endNode.getPosition());
            for (var i = 0; i < count; i++) {
                // console.log(beginPos);
                // console.log(endPos);
                this.coinFly(beginPos, endPos, i);
            }
        },

        zhuamaAni:function (zhuamarr,time) {
            for(var i = 0 ; i < zhuamarr.length ; i++){
                var beginPos = zhuamarr[i].beginPos;
                var uid = zhuamarr[i].uid;
                var row = uid2position[uid];
                var infoCasterHead = $('info' + row + '.head');
                var endPos = infoCasterHead
                    ? infoCasterHead.getParent().convertToWorldSpace(infoCasterHead.getPosition())
                    : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);

                var sprite = new cc.Sprite(majiang.res.zhuaniao);
                sprite.setScale(1.5);
                sprite.setPosition(cc.p(beginPos.x, beginPos.y));
                this.addChild(sprite,1000);
                (function (a,b) {
                    a.runAction(cc.sequence(
                        cc.delayTime(time),
                        cc.moveTo(0.5, cc.p(b.x - 5, b.y - 10)),
                        cc.delayTime(0.2),
                        cc.removeSelf()
                    ));
                })(sprite,endPos);

            }
            this.scheduleOnce(function () {
                cc.eventManager.dispatchCustomEvent('onExit_ZhuaMaLayer');
            },time+1)
           
        },
        //一个金币飞舞
        coinFly: function (beginPos, endPos, i) {
            var sprite = new cc.Sprite(res.goldTexture);
            sprite.setPosition(cc.p(beginPos.x, beginPos.y));
            this.getChildByName('Scene').addChild(sprite);
            sprite.runAction(cc.sequence(
                cc.delayTime(0.1 * i),
                cc.moveTo(0.5, cc.p(endPos.x - 5, endPos.y - 10)),
                cc.delayTime(0.2),
                cc.callFunc(function () {
                    sprite.removeFromParent(true);
                })
            ));
        },
        getOriginalPos: function () {
            return 2;
        },
        getEffectEmojiPos: function (caster, patient, isNotMid) {
            var self = this;
            var pos = {};
            var infoCasterHead = $('info' + caster + '.head');
            var infoPatientHead = $('info' + patient + '.head');
            pos[caster] = infoCasterHead
                          ? infoCasterHead.getParent().convertToWorldSpace(infoCasterHead.getPosition())
                          : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
            pos[patient] = (patient != self.getOriginalPos() && infoPatientHead) || isNotMid
                           ? infoPatientHead.getParent().convertToWorldSpace(infoPatientHead.getPosition())
                           : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
            return pos;
        },

        /**
         * 选飘
         * @private
         * */
        _onSelectedPiao: function (data) {
            this._hideReady();
            this.hideGuiPanel();
            this.clearTable4StartGame(true);
            this._refreshRoomState(majiang.RoomState.ONGOING);
            this._refreshRoundAndPai(false);
            var selected = data['selected'] || [];
            for (var i = 0; i < selected.length; i++) {
                var o = selected[i];
                if (o.piao > 0) {
                    var piao = $('info' + uid2position[o.uid] + '.piao');
                    if (cc.sys.isObjectValid(piao)) {
                        piao.setVisible(true);
                        piao.setTexture(majiang.res['word_' + o.piao]);
                    }
                }
                if (o.piao < 0) {
                    safeHide($('info' + uid2position[o.uid] + '.piao'));
                    if (o.uid === gameData.uid) {
                        if (cc.sys.isObjectValid(this.selectedPiao)) {
                            this.selectedPiao.removeFromParent(true);
                        }
                        this.selectedPiao = new SelectedPiao();
                        this.addChild(this.selectedPiao);
                    }
                }
            }
        },

        /**
         * 选飘结果
         * @private
         * */
        _onPiao: function (data) {
            var uid = data['uid'] || -1;
            var piao = data['piao'] || -1;
            var piaoSp = $('info' + uid2position[uid] + '.piao');
            if (cc.sys.isObjectValid(piaoSp) && piao > 0) {
                piaoSp.setVisible(true);
                piaoSp.setTexture(majiang.res['word_' + piao]);
            }
            if (gameData.uid === uid) {
                if (cc.sys.isObjectValid(this.selectedPiao)) {
                    this.selectedPiao.removeFromParent(true);
                }
            }
        },

        /**
         * 胡牌按钮特殊处理
         * @private
         * */
        _handleSpeacilHu: function (pai_id) {
            var self = this;
            console.log('胡牌按钮特殊处理【胡类型】' + this._huType + '牌：' + pai_id);
            var cpghg = $('cpghg');
            var hu = cpghg.getChildByName('hu');
            var hu_wang = cpghg.getChildByName('hu_wang');
            if (this._huType === majiang.Hu.ZiMo) {
                hu.setVisible(true);
                if (cc.sys.isObjectValid(hu_wang)) {
                    hu_wang.removeFromParent(true);
                }
                return;
            }
            network.stop();
            // 特么摸得牌暂时不显示
            safeHide(hu);
            if (!cc.sys.isObjectValid(hu_wang)) {
                hu_wang = new cc.Sprite(majiang.res.btn_wangdiao);
                hu_wang.setName('hu_wang');
                cpghg.addChild(hu_wang);
            }
            hu_wang.x = hu.x;
            hu_wang.y = hu.y;
            TouchUtil.removeListeners(hu_wang);
            TouchUtil.setOnclickListener(hu_wang, function () {
                network.start();
                self.sendChiPengGang(OP_HU, 2, pai_id);
                self.hideChiPengGangHu();
            });

            // 胡字按钮特殊处理
            switch (this._huType) {
                case majiang.Hu.WangDiao:
                    hu_wang.setTexture(majiang.res.btn_wangdiao);
                    self.showBtnActAnimation(hu_wang, "wangdiao", true);
                    break;
                case majiang.Hu.WangChuang:
                    hu_wang.setTexture(majiang.res.btn_wangchuan);
                    self.showBtnActAnimation(hu_wang, "wangchuang", true);
                    break;
                case majiang.Hu.WangDiaoWang:
                    hu_wang.setTexture(majiang.res.btn_wangdiao);
                    self.showBtnActAnimation(hu_wang, "wangdiao", true);
                    break;
                case majiang.Hu.WangChuangWang:
                    hu_wang.setTexture(majiang.res.btn_wangchuan);
                    self.showBtnActAnimation(hu_wang, "wangchuang", true);
                    break;
                default:
                    hu_wang.removeAllChildren();
                    break;
            }
        },

        /**
         * 吃碰杠胡听
         * @param {Object} data
         * @private
         * */
        _onChiPengGangHuTing: function (data) {
            this._hideReady();
            this._refreshRoundAndPai();
            this._huType = majiang.Hu.ZiMo;
            var self = this;

            var setCards = function (target, card_arr) {
                var childs = target.getChildren();
                for (var m = 0; m < childs.length; m++) {
                    safeHide($('' + m, target));
                }

                var card_count = card_arr.length;
                for (var i = 0; i < card_count; i++) {
                    var card = $('' + i, target);
                    if (!card) {
                        card = duplicateNode($('row2.c0.b0'),true);
                        card.setName('' + i);
                        card.setPosition($('n', target).getPosition());
                        target.addChild(card);
                    }
                    card.pai_id = card_arr[i];
                    card.setVisible(true);
                    var name = getPaiNameByRowAndId(2, card_arr[i], true);
                    setSpriteFrameByName(card, name, self.getPaiPlist());
                    card.setUserData({paiId: card_arr[i]});
                }
                var offset_x = 0;
                var bg = $('bg', target);
                var contentSize = bg.getContentSize();
                if (card_count > 1) {
                    offset_x = 65 * (card_count - 1);
                    contentSize.width = 108 + offset_x;
                    bg.setContentSize(contentSize);
                } else {
                    contentSize.width = 108;
                    bg.setContentSize(contentSize);
                }
                bg.setVisible(true);
                return offset_x;
            };

            // 操作对象
            var OpType = {
                Chi: 0,
                Peng: 1,
                Gang: 2,
                Hu: 3,
                Ting: 4
            };
            var op_map = {};
            for (var key in OpType) {
                if (OpType.hasOwnProperty(key)) {
                    op_map[OpType[key]] = [];
                }
            }
            var tishi = data['tishi'];
            for (var index = 0; index < tishi.length; index++) {
                var pai_id = tishi[index]['pai_id'];
                var op = tishi[index]['op'] || [false, false, false, false, false];
                for (var op_idx = 0; op_idx < op.length; op_idx++) {
                    if (op[op_idx]) {
                        op_map[op_idx].push(pai_id);
                    }
                }
                if (tishi[index]['huType']) {
                    this._huType = tishi[index]['huType'];
                }
            }
            cc.log('op_map ==== ', op_map);
            if (!isReplay) {
                var cpghg = $('cpghg');
                var chi = $('cpghg.chi');
                var peng = $('cpghg.peng');
                var gang = $('cpghg.gang');
                var hu = $('cpghg.hu');
                var ting = $('cpghg.ting');
                var guo = $('cpghg.guo');
                safeShow(cpghg);
                safeHide(chi);
                safeHide(peng);
                safeHide(gang);
                safeHide(hu);
                safeHide(ting);
                safeHide(guo);

                var show_arr = [];    // 王钓时点过显示的节点
                var node_arr = [];    // 操作节点数组
                var op_arr = [];      // 可操作的数组
                var node_offset = []; // 操作节点偏移量
                var pai_id = -1;
                if (op_map[OpType.Chi].length > 0) {
                    node_arr.push(chi);
                    op_arr.push(OP_CHI);
                    pai_id = op_map[OpType.Chi][0];
                    TouchUtil.setOnclickListener(chi, function () {
                        self.showChiLayer(pai_id, function (paiId, oriPaiId) {
                            self.sendChiPengGang(OP_CHI, 2, paiId, oriPaiId);
                        });
                    });
                    node_offset.push(setCards(chi, op_map[OpType.Chi]));
                }
                if (op_map[OpType.Peng].length > 0) {
                    node_arr.push(peng);
                    op_arr.push(OP_PENG);
                    pai_id = op_map[OpType.Peng][0];
                    TouchUtil.setOnclickListener($('cpghg.peng'), function () {
                        self.sendChiPengGang(OP_PENG, 2, pai_id);
                        self.hideChiPengGangHu();
                    });
                    node_offset.push(setCards(peng, op_map[OpType.Peng]));
                    show_arr.push(peng);
                }
                if (op_map[OpType.Gang].length > 0) {
                    node_arr.push(gang);
                    op_arr.push(OP_GANG);
                    var card_arr = op_map[OpType.Gang] || [];
                    node_offset.push(setCards(gang, card_arr));
                    TouchUtil.removeListeners(gang);
                    if (card_arr.length > 1) {
                        for (var idx = 0; idx < card_arr.length; idx++) {
                            (function (idx) {
                                var pai = $('' + idx, gang);
                                TouchUtil.removeListeners(pai);
                                TouchUtil.setOnclickListener(pai, function () {
                                    self.sendChiPengGang(OP_GANG, 2, pai.pai_id);
                                    self.hideChiPengGangHu();
                                });
                            })(idx);
                        }
                    } else {
                        TouchUtil.setOnclickListener(gang, function () {
                            self.sendChiPengGang(OP_GANG, 2, card_arr[0]);
                            self.hideChiPengGangHu();
                        });
                    }
                    show_arr.push(gang);
                }
                if (op_map[OpType.Hu].length > 0) {
                    node_arr.push(hu);
                    op_arr.push(OP_HU);
                    pai_id = op_map[OpType.Hu][0];
                    TouchUtil.setOnclickListener(hu, function () {
                        network.start();
                        self.sendChiPengGang(OP_HU, 2, pai_id);
                        self.hideChiPengGangHu();
                    });
                    node_offset.push(setCards(hu, op_map[OpType.Hu]));
                }
                if (op_map[OpType.Ting].length > 0) {
                    node_arr.push(ting);
                    op_arr.push(OP_TING);
                }
                node_arr.push(guo);

                TouchUtil.setOnclickListener(guo, function () {
                    if (self._huType !== 0 && network._isStop) {
                        for (var show_idx = 0; show_idx < show_arr.length; show_idx++) {
                            safeShow(show_arr[show_idx]);
                        }
                        network.start();
                        return;
                    }
                    if (op_map[OpType.Hu].length > 0 && self.isMyTurn()) {
                        // showMessageBox('您当前可以自摸, 确定要点【过】吗?', function () {
                        self.sendChiPengGang(OP_PASS, 2, pai_id);
                        self.hideChiPengGangHu();
                        // });
                    } else {
                        self.sendChiPengGang(OP_PASS, 2, pai_id);
                        self.hideChiPengGangHu();
                    }
                });

                // 位置适配
                index = 0;
                var node_count = node_arr.length;
                var total_offset_x = 0;
                for (; index < node_arr.length; index++) {
                    safeShow(node_arr[index]);
                    node_arr[index].setPositionX(posConf.cpghgPositionX[node_count][index] + total_offset_x);
                    total_offset_x += node_offset[index];
                }
                this.countDown(12);

                // 胡牌按钮特殊处理
                var hu_wang = cpghg.getChildByName('hu_wang');
                if (cc.sys.isObjectValid(hu_wang)) {
                    hu_wang.removeFromParent(true);
                }
                if (op_map[OpType.Hu].length > 0) {
                    this._handleSpeacilHu(op_map[OpType.Hu][0]);
                    if (this._huType !== majiang.Hu.ZiMo) {
                        for (var show_idx = 0; show_idx < show_arr.length; show_idx++) {
                            safeHide(show_arr[show_idx]);
                        }
                    }
                }
            }
        },
        //获取自己的ChatInfo节点
        getChatInfoNode:function (idx) {
            var self = this;
            var ChatInfoNode = null;
            if($('info' + idx)){
                ChatInfoNode = $('info' + idx + '.ChatInfo');
            }
            return ChatInfoNode;
        },
        getPaiPlist: function () {
            return majiang.res.pai0plist;
        },
        /**
         * 显示吃碰胡动画
         * @param pNode
         * @param aniName
         * @param isloop
         */
        showActAnimation: function (pNode, aniName, isloop) {
            var self = this;
            if (!cc.sys.isObjectValid(pNode) || aniName == '') {
                return;
            }
            pNode.removeAllChildren();
            pNode.setOpacity(255);

            var tmpNode = pNode;
            var spineAni = playSpine(majiang.res.sp_majiang_zi_json, aniName, isloop, function () {
                setTimeout(function () {
                    tmpNode.removeAllChildren();
                    tmpNode.setOpacity(0);
                }, 100);
            });
            pNode.addChild(spineAni);
            pNode.setScale(1.5, 1.5);
        },
        /**
         * 显示吃碰胡动画
         * @param pNode
         * @param aniName
         * @param isloop
         */
        showBtnActAnimation: function (pNode, aniName, isloop) {
            var self = this;
            if (!cc.sys.isObjectValid(pNode) || aniName == '') {
                return;
            }
            pNode.removeAllChildren();
            pNode.setOpacity(255);

            var spineAni = playSpine(majiang.res.sp_majiang_btn_json, aniName, isloop, function () {
            });
            spineAni.setPosition(cc.p(pNode.getContentSize().width / 2, pNode.getContentSize().height / 2));
            pNode.addChild(spineAni);
            pNode.setScale(1.2, 1.2);

        },
        /**
         * 展示开局动画
         */
        setUpGameStartAnimation: function () {
            var self = this;
            //添加开局动画
            var showAnimation = function (pNode, aniName, isloop) {
                if (!cc.sys.isObjectValid(pNode) || aniName == '') {
                    return;
                }
                pNode.removeAllChildren();
                pNode.setOpacity(255);

                var tmpNode = pNode;
                var spineAni = playSpine(majiang.res.sp_majiang_kaiju_json, aniName, isloop, function (){
                    setTimeout(function () {
                        tmpNode.removeAllChildren();
                        tmpNode.setOpacity(0);
                    }, 2000);
                });
                pNode.addChild(spineAni);
                pNode.setScale(1.2, 1.2);
            };
            showAnimation($('centerPos'), "kaiju", false);
        }
    });
    exports.Mahjong.getPaiNameByRowAndId = getPaiNameByRowAndId;
})(window);
